Page 174 - Open Soource Technologies 304.indd
P. 174
Unit 10: Cookies
By changing the value of session.auto_start to 1, you ensure that a session is initiated for Notes
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 10.1 starts a session
and prints the session ID to the browser.
Example: 1. Starting or Resuming a Session
1: <?php
2: session_start();
3: ?>
4: <html>
5: <head>
6: <title>Listing 10.1 Starting or resuming a session</title>
7: </head>
8: <body>
9: <?php
10: echo “<p>Your session ID is “.session_id().”</p>”;
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.
Accessing a unique session identifier in each of your PHP documents is only the start of session
functionality. When a session is started, you can store any number of variables in the $_SESSION
superglobal and then access them on any session-enabled page.
LOVELY PROFESSIONAL UNIVERSITY 169