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

Get PHP in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.