PHP and MySQL Programming/Session Handling

HTML and PHP are "stateless" languages. Meaning that they are incapable of retaining a state between pages. To get around this serious limitation, we use sessions. With sessions, session variables are stored in a file on the web server and so are accessible across multiple pages.

Starting a Session
Before we can start using session variables, we need to start a session. This needs to be done on every page that makes use of session variables. It is important to note that a session must be started before anything is outputted. Here is the code to start a session:

Please make sure that there are NO SPACES before the "$_SESSION[] array variable. Here is an example:

Retrieving Session Variables
Once a session is created, and variables are stored, they may be retrieved from the $_SESSION[] array. Here is an example:

The above example starts a session, then checks if the session variable 'user_name' has been created (with the isset function), if it has, then it assigns its value to $user_name, and prints it to the screen.

Destroying a Session
To destroy a session, we use the session_destroy function. This is useful if we want to, for example, log a user off of a web-application. Thus we would use the following code:

Note that we first need to start the session before we destroy it. This is because the session_destroy function destroys the currently active session.