Starting a Session

To work with a session, you need to explicitly start or resume that session unless you have changed your php.ini configuration file. By default, sessions do not start automatically. If you want to start a session this way, you will have to find the following line in your php.ini file and change the value from 0 to 1 (and restart the Web server):

session.auto_start = 0

By changing the value of session.auto_start to 1, you ensure that a session is initiated for every PHP document. If you don't change this setting, you need to call the session_start() function in each script.

After a session is started, you instantly have access to the user's session ID via the session_id() function. session_id() allows you to either set or get a session ID. Listing 16.1 starts a session and prints the session ID to the browser.

Listing 16.1 Starting or Resuming a Session
  1: <?php
  2: session_start();
  3: ?>
  4: <html>
  5: <head>
  6: <title>Listing 16.1 Starting or resuming a session</title>
  7: </head>
  8: <body>
  9: <?php
 10: print "<p>Your session ID is ".session_id()."</p>\n\n";
 11: ?>
 12: </body>
 13: </html>

When this script is run for the first time from a browser, a session ID is generated by the session_start() function call on line 2. If the page is later reloaded or revisited, the same session ID is allocated to the user. This action assumes that the user has cookies enabled. For example, when I run this script the first time, the output is

Your session ID is fa963e3e49186764b0218e82d050de7b

When I reload the page, the output is still

Your session ID is fa963e3e49186764b0218e82d050de7b

because I have cookies enabled and the session ID still exists.

Because start_session() attempts to set a cookie when initiating a session for the first time, it is imperative that you call this function before you output anything else at all to the browser. If you do not follow this rule, your session will not be set, and you will likely see warnings on your page.

Sessions remain current as long as the Web browser is active. When the user restarts the browser, the cookie is no longer stored. You can change this behavior by altering the session.cookie_lifetime setting in your php.ini file. The default value is 0, but you can set an expiry period in seconds.

    Part III: Getting Involved with the Code