PHP Sessions

From Wikiversity
Jump to navigation Jump to search

Just what are sessions?[edit]

Sessions are a method to store information relating to a user in an environment where the user has no direct control. They can be thought of as cookies that are stored on the web server, as opposed to the user's browser.

How to use sessions[edit]

Before using sessions in any way, shape or form you need to start the session. This is done by calling the session_start() function before any HTTP headers have been sent, i.e. before anything has been echoed or printed to the browser. Note that any errors that occur will be sent to the browser (depending on your PHP configuration).

Session information is stored in a special variable called $_SESSION. It is very easy to get and set elements that are added to this special array.

 session_start();
 $_SESSION['username'] = 'Nick';
 echo $_SESSION['username'];

Now this may not seem very clever, in fact, it may look like a waste of energy and time doing this, but the real beauty can be seen when we navigate to another page that looks like the following:

 session_start();
 echo $_SESSION['username'];

The above will echo Nick assuming we visited the first page previously.

Sessions and security[edit]

When dealing with sessions, a unique key is assigned to the user, the Session key. This key is commonly stored as a cookie on the user's machine, and only lasts as long as the browser is open. The session key is the string that is used to fetch the session information on the server.

Common sense dictates that if this session key was to be given to another individual, then it would be possible for that individual to gain access to the session that the user was using, compromising the session's integrity.

It is for this reason that it would make sense to regenerate this session key every once in a while. This can be done easily by using the session_regenerate_id() function.

To delete a session completely, the function session_destory() should be used.