PHP Basic Series – Session Handling

A session, a lasting connection between a user agent (user browser) and a server application (web application, site, etc) have a very short time life just like a cookie therefore it caries all the information necessary to the application to communicate between all of its parts.

The lasting connection, a true characteristic of a session, is also the reason why is important to take a very careful look at how the session works and how to increase its security.

In order to facilitate things and understanding of session, consider the session as a cookie holds an array and it is stored at the server while the application is being executed (or until your browser closes).

In PHP a session can be either stored in the filesystem or in the database. Either choice of storage has its pros and cons regarding security but in the overall both work in the same way. Consider the previous example: The login form. Once the user connects correctly logs into the application is necessary to keep the username / password or username / logged state so all parts of the application understands that the current user has correctly logged at some point and will keep like that until he decides to logoff.

To correctly construct that scenario the first thing to be done is to set the session. With PHP, unless you specify it, a session will not be started. There are 2 ways to start a session:

  1. You open the session on every single script of your application using <?php session_start(); ?>
  2. You open it only once, at the application bootstrap, and includes the bootstrap in every step of the application

It might seem that both are the same, therefore the second option is by far more clean and secure.

bootstrap.php

<?php
session_start(); // the session start must be the first thing of every script. If any header or even an echo is done before the session start, it will break
// Adding some security to avoid session fixation attacks
if (!isset($_SESSION[‘sinit’])) {
session_regenerate_id(); // this will give the session a new identifier and keep the current session information
$_SESSION[‘sinit’] = true;
}
// the bootstrap file is also a good place to start libraries such as ob_start and to define your constants that will be shared all over the application
// since it’s a full php file, with no HTML coding (or any other coding), there is no need to close the PHP open tag

At the bootstrap the application now have the session instantiated and also have a small security that checks if the sinit (session initiated) session variable has already being set and otherwise it will regenerate the session identifier keeping the previous data. This will help your application to prevent from the most usual Session Fixation attacks.

The bootstrap is prepared and the next step is to include the bootstrap on the login script. The bootstrap will add the initiated session on the login script and the application will be able to use the session to hold the login information from the user, so it can be used in other parts of the application.

login.php

<?php
include_once(‘bootstrap.php’); // getting the instantiated session and variables

if (isset($_POST[‘doIt’])) {

// initiating the session variables that will hold the logged user information
$_SESSION[‘username’] = null;
$_SESSION[‘logged’] = false;

$username = $_POST[‘username’];
$password = (int) $_POST[‘password’]; // casting the password so it can be converted to a integer since everything on a post variable is, at first, a string

if ( (!empty($username) && is_string($username) && $username === ‘myUsername’)
(!empty($password) && is_numeric($password) && $password === 123456789)) {
// for now let’s use a hardcoded username and a hardcoded password just to exemplify the process
// the username and password is correct and the user is correctly logged on. Now is necessary to tell the remaining parts of the application.

$_SESSION[‘username’] = $username;
$_SESSION[‘logged’] = true;

header(‘location: userProfile.php’);
}
?>
<html> ….

With the code snipped above the application now holds the information that the user myUsername is now logged and there is no more need to requested for the user to login or force his logout.

This code would not make much sense if we don’t use it in other parts of the system. Let’s add on this little application 2 more sections, the user profile and a logout page to clean the session.

userProfile.php

<?php
include_once(‘bootstrap.php’);

if (!isset($_SESSION[‘username’]) || !isset($_SESSION[‘logged’]) || !$_SESSION[‘logged’]) {
// checking if the user is logged, otherwise, redirect to logout
header(‘location:logout.php’);
}
?>
<html>
<head>
<title> User Profile </title>
</head>
<body>
<h3>Welcome to your profile page, <?php echo $_SESSION[‘username’]; ?></h3>
<fieldset>
<legend>Action Menu </legend>
<dl>
<dt> Edit your profile </dt>
<dt> <a href=”logout.php”>Logout</a> </dt>
</dl>
</fieldset>
</body>
</html>

At the user profile the application checks the session to see if the user is correctly logged and otherwise redirects the user-to-be to the logout page that will clean the session and redirects him to the login page. At the user profile page the application makes use of the information in hands and uses to interact with the user (in blue). When the page is displayed it will show:

Welcome to your profile page, myUsername

Bellow the message it will show the user some action options for editing his profile information and loggout of the application.

To finish up, let’s clean the session once the user is ready to logout.

logout.php

<?php
include_once(‘bootstrap.php’);
// cleaning the session variables
$_SESSION = array();

if (isset($_COOKIE[session_name()])) {
// to guarantee that the previous session will not be hijacked, destroy the cookie that held the session name
setcookie(session_name(), ”, time() – 42000, ‘/’);
}

// finally destroy the session
session_destroy();

header(‘location: index.php’);

This will fully clean up the session and redirect the user to the first page of the application. It seems a simple set of scripts all over but this will fully exemplify how the session should be handled through the application.

The basics still being, for every session instantiated it must have a session destroy and clean up part. Managing variables, creating, destroying, adding values and updating, works in the same way as an array, but in this case the array is handled by the system and it has its own name $_SESSION.

The series is getting close to the end and soon enough everything will be set together. Keep learning and playing with the session and check this 2 articles from Chris Shiflett blog. It shows very well how session and security should be walking side by side.

  1. Session Fixation
  2. Session Hijacking

Have fun.

Advertisements

About mcloide

Making things simpler, just check: http://www.mcloide.com View all posts by mcloide

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: