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. The session_id() function allows you to either set or retrieve a session ID. Listing 12.2 starts a session and prints the session ID to the browser.

Listing 12.2. Starting or Resuming a Session

 1: <?php 2: session_start(); 3: echo "<p>Your session ID is ".session_id().".</p>"; 4: ?>

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 script 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.

Sams Teach Yourself PHP, MySQL And Apache All in One
Sams Teach Yourself PHP, MySQL and Apache All in One (3rd Edition)
ISBN: 0672328739
EAN: 2147483647
Year: 2004
Pages: 327 © 2008-2017.
If you may any questions please contact us: