PHP COTW: sessions

In this weeks PHP code of the week we cover the use of session; how to create, add, extract and delete them.

Sessions are another way that you can store information about a user and use that information on another page. They work by storing temporary information in a session id which is stored on the local user’s computer or is passed through in the URL. Sessions must be the first thing listed in the PHP file or else you’ll run into problems.

Below is an example of how the session function would be used in a file and how we store information in the session.

header(“Cache-control: private”); //IE 6 Fix

$_SESSION[‘username’] = $form_username;
$_SESSION[‘password’] = $form_password;[/php]

Firstly we start/access the session using the session_start() function and below that is just an IE 6 Fix for session. We the use the $_SESSION[‘name’] to store information into the session.

Checking for a session is simple and you can check the specific variable name you assigned. We can extract session information as we did with cookies.

[php]if($_SESSION[‘username’]) {

// Session present code
$username = $_SESSION[‘username’]);
$password = $_SESSION[‘password’]);


To remove the session we unset all the of session data and then we destroy the session.

[php]$_SESSION = array();

There you have an overview on how to use sessions. Sessions are similar to cookies and are being used more often than cookies. In the next PHP code of the week we’ll cover using creating, editing and deleting files in PHP

Leave a Reply