O'Reilly logo

Learning PHP 5 by David Sklar

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Storing and Retrieving Information

Session data is stored in the $_SESSION auto-global array. Read and change elements of that array to manipulate the session data. Example 8-9 shows a page counter that uses the $_SESSION array to keep track of how many times a user has looked at the page.

Example 8-9. Counting page accesses with a session

session_start( );

$_SESSION['count'] = $_SESSION['count'] + 1;

print "You've looked at this page " . $_SESSION['count'] . ' times.';

The first time a user accesses the page in Example 8-9, no PHPSESSID cookie is sent by the user's web client to the server. The session_start( ) function creates a new session for the user and sends a PHPSESSID cookie with the new session ID in it. When the session is created, the $_SESSION array starts out empty. So, $_SESSION['count'] = $_SESSION['count'] + 1 sets $_SESSION['count'] to 1. The print statement outputs:

You've looked at this page 1 times.

At the end of the request, the information in $_SESSION is saved into a file on the web server associated with the appropriate session ID.

The next time the user accesses the page, the web client sends the PHPSESSID cookie. The session_start( ) function sees the session ID in the cookie and loads the file that contains the saved session information associated with that session ID. In this case, that saved information just says that $_SESSION['count'] is 1. Next, $_SESSION['count'] is incremented to 2 and You've looked at this page 2 times. is printed. Again, at the ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required