Skip to Main Content
PHP in a Nutshell
book

PHP in a Nutshell

by Paul Hudson
October 2005
Intermediate to advanced content levelIntermediate to advanced
372 pages
11h 35m
English
O'Reilly Media, Inc.
Content preview from PHP in a Nutshell

Using Sessions

Sessions store temporary data about your visitors and are particularly good when you don't want that data to be accessible from outside of your server. They are an alternative to cookies if the client has disabled cookie access on her machine, because PHP can automatically rewrite URLs to pass a session ID around for you.

Starting a Session

A session is a combination of a server-side file containing all the data you wish to store, and a client-side cookie containing a reference to the server data. The file and the client-side cookie are created using the function session_start() —it has no parameters but informs the server that sessions are going to be used.

When you call session_start(), PHP will check to see whether the visitor sent a session cookie. If it did, PHP will load the session data. Otherwise, PHP will create a new session file on the server, and send an ID back to the visitor to associate the visitor with the new file. Because each visitor has his own data locked away in his unique session file, you need to call session_start() before you try to read session variables—failing to do so will mean that you simply will not have access to his data. Furthermore, as session_start() needs to send the reference cookie to the user's computer, you need to have it before the body of your web page—even before any spaces.

Adding Session Data

All your session data is stored in the session superglobal array, $_SESSION, which means that each session variable is one element ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe
Learning PHP

Learning PHP

David Sklar

Publisher Resources

ISBN: 0596100671Errata Page