Hacking with PHP has been updated for PHP 7 - click here! >>

Starting a session

bool session_start ( void )

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 their own data locked away in their 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 their 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.


If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: Adding session data >>

Previous chapter: Using sessions

Jump to:


Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.