Using Sessions in PHP

Using Sessions in PHP

This tutorial covers the session handling in PHP. It provides examples to create, update, and destroy the sessions in PHP. It also provides examples to set, read, and remove the session variables in PHP.

April 23, 2020

This tutorial provides examples to handle sessions in PHP. It provides examples to create, update, and destroy sessions in PHP.

Why Do We Need Sessions In PHP?

We can store temporary data of client applications communicating with the server by using Cookies or Sessions. The major issue with cookies is that the data is stored on the client-side i.e. the browsers and the attackers can easily modify the cookie data by stealing it which might expose the identity, user data, or inject malicious code including SQL injection. So, it's always preferred to use SSL to transfer encrypted cookies and store only the data which does not reveal the user's identity or personal data. Cookies also add up to the network bandwidth since the client applications always send the cookie data to the server and the server returns it back with every request.

We can also use Sessions to store temporary data on the server-side. This will not expose the data directly to the clients and avoid the additional network bandwidth required to send and receive the temporary data. PHP generates random session IDs which are hard to guess and associate unique session Id with every client.

The most common usage of Sessions in PHP is to track the logged-in users. The session can be created on login success and it can be destroyed on logout. The intermediate requests and pages can access the user by using the session variable. Also, we can show the error message and asks the user to log-in back if the user accesses the private pages on session timeout.

Start a Session In PHP

We can use the function session_start to start a new session. It will create a new session and also generate a unique session id to be associated with the client application. The example code to start a session is shown below.

<?php
// Start the session if not exist
session_start();

This simply starts a session by generating the unique session id. It internally checks whether a session id already exists for the same client. In such cases, it resumes the existing session without creating a new one.

Store Session Data

We can create, update, or remove session variables by using the $_SESSION superglobal array. The other superglobal arrays in PHP includes $_GET, $_POST, $_REQUEST, $_FILES, $_COOKIE, and $_SERVER. The $_SESSION superglobal array can be used as shown below.

<?php
// Start the session if not exist
session_start();

....
....
// Code to process the form data
....
....

// Store session data
$_SESSION[ 'name' ] = "Mack";
$_SESSION[ 'age' ] = 25;

We can also remove the session variable by using the unset function as shown below.

// Remove session variable
if( isset( $_SESSION[ 'age' ] ) ) {

unset( $_SESSION[ 'age' ] );
}

Access Session Data

We can access the session variables by using the $_SESSION superglobal array as shown below.

<?php
// Start the session if not exist
session_start();

// Read session data
$name = null;
$age = null;

if( isset( $_SESSION[ 'name' ] ) ) {

$name = $_SESSION[ 'name' ];
}

if( isset( $_SESSION[ 'age' ] ) ) {

$age = $_SESSION[ 'age' ];
}

....
....
// Use $name and $age session variables

Below mentioned is another example of the session variable to keep track of the existing variable and updating it by using the existing value.

if( !isset( $_SESSION[ 'count' ] ) ) {

$_SESSION[ 'count' ] = 0;
}
else {

$_SESSION[ 'count' ]++;
}

Destroy Session

We can also destroy the session data which completes removes all the session variables. We cannot access the session variables after calling the session_destroy function. The session_unset function can also be used in case we want to keep the same session by first storing the important session variables and call it to clear all other variables. We can again store the important session variables back to the same session.

<?php
// Start the session if not exist
session_start();

// Read session data
$name = null;
$age = null;

if( isset( $_SESSION[ 'name' ] ) ) {

$name = $_SESSION[ 'name' ];
}

if( isset( $_SESSION[ 'age' ] ) ) {

$age = $_SESSION[ 'age' ];
}

....
....
// Use $name and $age session variables
....
....

// Remove all the session variables
session_unset();

// Destroy the session
session_destroy();

By default, the PHP session data lasts for 24 minutes in the absence of any user activity. Also, make sure that the function session_destroy is called after session_start. We can also timeout PHP sessions as discussed in Set Timeout For Session In PHP.

Summary

This tutorial provided the usage of sessions in PHP by providing the appropriate examples to start the session. It also provided examples to create, update, or remove a variable from the session. At last, we have destroyed the session to clear the temporary data on the server.

Write a Comment
Click the captcha image to get new code.
Discussion Forum by DISQUS