Php Sessions

Sessions are a useful part of php that allow you to store certain information about a user while they are visiting your site. The main use is for keeping people logged onto your site or forums without lots of cookies. The information stored with sessions is kept on the server so malicious users cannot change it.

The way they work is by giving the user an ID for their visit. This is usually stored in a session cookie which is deleted when the browser is closed. It is very rare for session cookies to be disabled but in this case the session ID is often tagged onto the end of urls. The server has a different set of data for each ID.

Because the session ID is stored in a cookie the server must request it in the headers. Because the headers have to be sent before the web page this means that the session initialisation process, which must happen on every page using sessions, has to be placed before any content (even spaces and new lines may cause an error). If there is content before the session initialisation then you will get a 'headers already sent' error. By content I am referring to non php code so you can have as much php code as you like before the session initialisation.

Initialising a session

This is when the session ID is fetched or created if it is a new user. The code for this is very simple. Remember to place it inside the php tags ().
session_start();
The web server takes care o all of the fancy stuff in the background.

Session variables

Technically the session data is stored in an array but I will call the values variables for simplicity. Session variables are used in exactly the same way as normal ones its just they are kept over all of your website.

A session variable is in this format: $_SESSION["varname"]

'varname' is replaced with the name for your session variable. varname is just a standard string so it is possible to use a string stored in a variable to access the variable like in this example:
$sessionvarname = "varname";
$_SESSION[$sessionvarname] = "Jim";
This code will set the 'varname' session variable's value to 'Jim'.

Thats how to use sessions. A complicated task made simple by php.

Back to php tutorials

© Jonathan Waller 2005; QuantumState Visual Basic