|[ Team LiB ]|
Starting a Session with session_start()
You need to explicitly start or resume a session unless you have changed your php.ini configuration file. By default, sessions do not start automatically. In php.ini, you will find a line containing the following:
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.
PHP uses files to store session data between requests so you should also check the session.save_path directive in your php.ini file. session.save_path defines the directory on your filesystem to which session files are saved. You should ensure that it exists and that your PHP process has permission to write to it:
session.save_path = "/tmp"
After a session has been 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 20.1 starts a session and prints the session ID to the browser.
1: <?php 2: session_start(); 3: ?> 4: <!DOCTYPE html PUBLIC 5: "-//W3C//DTD XHTML 1.0 Strict//EN" 6: "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 7: <html> 8: <head> 9: <title>Listing 20.1 Starting or Resuming a Session</title> 10: </head> 11: <body> 12: <?php 13: print "<p>Welcome, your session ID is ".session_id()."</p>\n\n"; 14: ?> 15: </body> 16: </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 presupposes, of course, that the user has cookies enabled on his browser. If you examine headers output by the script in Listing 20.1, you can see the cookie being set:
HTTP/1.1 200 OK Date: Tue, 26 Aug 2003 16:54:44 GMT Server: Apache/2.0.47 (Unix) PHP/5.0.0b1 X-Powered-By: PHP/5.0.0b1 Set-Cookie: PHPSESSID=b3228ce5e66834bc2ced42a899328796; path=/ Expires: Thu, 19 Nov 1981 08:52:00 GMT Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0 Pragma: no-cache Connection: close Content-Type: text/html; charset=ISO-8859-1
Because start_session() attempts to set a cookie when initiating a session for the first time, you need to call it before you output anything else to the browser. Notice that no expiry date is set in the cookie that PHP sets for the session. This means that the session remains current only as long as the browser is active. When the user restarts his browser, the cookie is not stored. You can change this behavior by altering the session.cookie_lifetime setting in your php.ini file. This defaults to 0, but you can set an expiry period in seconds. This causes an expiry date to be set for any session cookies sent to the browser.
|[ Team LiB ]|