Changing the PHP Session Behavior

As part of PHP’s support for sessions, there are over 20 different configuration options you can set for how PHP handles sessions. Here I’ll highlight a few of the most important ones here. Note two rules about changing the session settings:

1. All changes must be made before calling session_start().
2. The same changes must be made on every page that uses sessions.

  ini_set (parameter, new_setting);

For example, to require the use of a session cookie (as mentioned, sessions can work without cookies but it’s less secure), use

   ini_set ('session.use_only_cookies', 1);

Another change you can make is to the the name of the session (perhaps to use a more userfriendly one). To do so, use the session_name() function.


The benefits of creating your own session name are twofold: it’s marginally more secure and it may be better received by the end user (since the session name is the cookie name the end user will see). The session_name() function can also be used when deleting the session cookie:

  setcookie (session_name(), '', time()-3600);

Finally, there’s also the session_set_cookie_params() function. It’s used to tweak the settings of the session cookie.

  session_set_cookie_params(expire, path, host, secure, httponly);

Note that the expiration time of the cookie refers only to the longevity of the cookie in the Web browser, not to how long the session data will be stored on the server.