php

PHP Session Tutorial

When a website of multiple pages is designed then it is not possible to store the state information of the pages without using session. When the user moves from one page to another, then it is essential to keep information of the previous page for different types of sites. But the stateless protocol HTTP is unable to do this task. One of the ways to solve this problem is using the PHP session handling feature. It is used to keep all information of each visitor such as: when the user has started visiting the site, which pages have been visited by the user, which activities have been done by the user on each page, and when the user has closed the site, etc. Session handling is very important for the e-commerce-based website where the user has to move to different pages to purchase products. Many PHP session directives, built-in functions, and variables are used by the PHP script to handle the user's session. The way of handling a user's session by using PHP configuration directives, session function, and session variables has been shown in this tutorial by using multiple examples.

PHP Session Directives

All session-related directives can be set by using the php.ini file. Some useful session-related PHP directives are mentioned.

Session Directive purpose
session.save_handler The value of the directive can be files or mm or sqlite or user. The mm is used to handle session data by using memory. The sqlite is used to handle data by using SQLite database. The user is used to handling data by using the user-defined function.
session_auto_start The value of this directive will be On to start the session automatically; otherwise, it will be Off.
session.name It is used to set the session name and the default session name is PHPSESSID.
session.save_path It is used to set the path where the session information will be stored. The default value of this directive is files.
session.hash_function It is used to generate a hashed session ID. 0 is used MD5 algorithm and 1 is used for the SHA algorithm.
session.cache_expire It is used to set the expiration time of the session.
session.use_cookies It is used to store the session ID by employing the cookie. 1 is used for employing cookies and 0 is emplyed for not using the cookie.
session.use_only_cookies It is used to employ the cookie only for storing the session ID.
session.cookie_secure It is used to define whether the cookie will employ the secure connection or not. It is enabled by using the ON and disabled by employing the Off values.
session.cookie_lifetime It is used to set the lifetime of the cookie.

You can visit the following link to know more about the session directives.

https://www.php.net/manual/en/ini.list.php

PHP Session Functions

PHP has many built-in functions for session handling tasks. Some useful session handling functions are mentioned below.

Session Function purpose
session_start() It is used to start a new session or restart the previous session.
session_id() It is used to set or get or both set and get the session ID.
session_create_id() It is used to create a new session ID.
session_name() It is used to set or get or both set and get the current session name.
session_status() It is used to get information about the current status of the session.
session_reset() It is used to re-initialize the session array.
session_unset() It is used to undefined all session variables.
session_destroy() It is used to destroy all registered session data.
session_encode() It is used to encode the current session data.
session_decode() It is used to decode the encoded current session data.
session_commit() It is used to write session data and close the session.
session_abort() It is used to remove the changes to the session array and close the session.
session_regenerate_id() It is used to generate a new session for the existing session.
session_cache_limiter() It is used to set or get the cache limiter of the current session.
Session_cache_expire() It is used to set or get the cache expire time of the current session.

You can visit the following link to know more about the built-in session functions of PHP: https://www.php.net/manual/en/ref.session.php.

PHP Session Variable

PHP uses an associative array named $_SESSION for storing session data. It is ‘superglobal’ variable that can be accessed from anywhere in the script. The values are initialized into this variable after creating a session and this variable becomes unset after destroying the session.

Session Handling

The session handling can be done by the web server by using the database or file. The session handling can be done by using the browser of the user if the browser supports the cookies. But if the cookies of the browser are disabled by the user then this way can’t be used for session handling. So, using the web server is the best way of handling sessions. The steps for session handling are mentioned below.

  • The visitor sends the request to the webserver to visit a page.
  • The web server creates a session ID for the visitor, stores session-related data for the visitor , and sends the page as the response for the visitor.
  • The web server saves the session information related to the visitor into a text file on the server to track the visitor’s session on each page visited by the visitor during the session.
  • If the browser that is used by the visitor supports cookies, the session ID will be stored by the PHPSESSID cookie to track the visitor’s session on each page visited by the visitor during the session.

Create and Print the Session ID

PHP has two built-in functions to create or restart a previous session and those mentioned earlier in this tutorial. The use session_start() function has been shown here that is used to generate a new session or re-generate a previous session. It checks the session exists for the visitor and creates a new session if the visitor visits the page the first time. Create a PHP file with the following script that creates a new session for the visitor and generates a unique session ID that has been printed by another built-in function named session_id().

<?php
//Start a new session
session_start();
//Print the session id
echo "Newly generated session id: <br/> <b>".session_id(). "</b>";
?>

Output
The following output will appear after executing the above script from the web browser. The unique session ID has been printed here and this ID will remain unchanged every time the page is refreshed. If the browser is closed and re-opened again to execute this script, a new session ID will be printed.

Store and Print the Session Data

The $_SESSION variable is required to be initialized after creating the session ID to store the session data. Create a PHP file with the following script that stores the value of the “name” key of the $_SESSION[] variable after starting a new session. The isset() function has been used in the script to check the $_SESSION[‘name’] variable is set or unset. If the value is unset for this variable, a value will be set for this variable. If the value has been set for this variable, the value of this variable will be printed with the formatting.

<?php
//Start a new session
session_start();

if(!isset($_SESSION['name']))
{
    echo "<br/><br/>";
    echo "<h2 style='text-align:center'>New session has been started for the user.</h2>";
    //Save the session data
    $_SESSION["name"] = "Fahmida Yesmin";
}
else
{
    echo "<br/><br/>";
    //Read the session data
    echo '<h2 style="text-align:center">Welcome back, ' . $_SESSION["name"] . '.</h3>';
}
?>

Output
The following output will appear after executing the above script the first time. According to the output, a new session ID has been generated for the visitor because the user visits the page for the first time. The $_SESSION[‘name’] variable has been initialized by a string value and a message has been printed for the new session.

The following output will appear if the user visits the page the next time. The value of the $_SESSION[‘name’] variable has been printed here. The following message will be displayed every time until the session is destroyed or the session data is removed or the browser is re-opened.

Create a Session After Authenticating the User

Normally, the session is created for the registered user of the website after authenticating the user based on the valid data to prevent unauthorized access to the user for the sensitive data. The session handling is very important for the e-commerce website to track the user’s activity.  The data related to the user’s authentication is stored in the database server like MySQL, SQLite, SQL Server, PostgreSQL, etc. The user information for the authentication has been stored in text here for simplicity. Create a text file named users.txt with the following content and the file contains the name, email, username, and password of three users. Each field is separated by a comma (,) in the file. The authentication will be verified by using the username or email and the password.

users.txt

name, email, username, password

Nipa Chowdhury, [email protected], nipa35, pop890

Mehrab Hossain, [email protected], hossainbd, 674523

Abbas Uddin, [email protected], abbas90, hello765

Create an HTML file named loginForm.html with the following script that will display a login form with two text fields and a submit button. The username or email will be taken in the first text field and the password will be taken in the second text field. When the submit button will press, the page will be redirected to session3.php which will be created later.

loginForm.html

<html>
<head>
<title>Session Handling using PHP</title>
</head>

<body>
    <div style="width:30%">
    <fieldset>
    <legend>Login</legend>
    <form method="post" action="session3.php">
    <p style="font-size:20px">username or email: <input type="text" name="useremail" /> </p>
    <p style="font-size:20px">password: <input type="password" name="password" /> </p>
    <p> <input type="submit" name="Submit" value="Submit" /> </p>
    </form>
    </fieldset>
</div>
</body>
</html>

Create a PHP file with the following script that authenticate the login information based on the data of the users.txt file and initializes the session data after authenticating the user. The $login variable has been used to trace whether the submitted login information is valid or invalid and the initial value of this variable is false. The first isset() function will be used to check if the $_SESSION[‘name’] variable is set or unset. If this variable is unset, the second isset() function will be used to check the value of $_POST[‘useremail’] variable. If the values of this variable are set, the submitted form values will be stored in two variables. If the values of these variables are non-empty, the users.txt file will be opened for reading to check the submitted form values match with the values of the email or username and the password of any user of the text file. The explode() function has been used to split each line of the file based on the comma(,) and store the splitted values into four variables. The trim() function has been used to remove extra space from both sides of the variable. If any matching entry is found, the $_SESSION[‘name’] variable will be initialized by the name of the matching user that was retrieved from the file and a success message,  “You are logged in successfully.” will be printed. If no matching entry is found, the login form will appear again. If the page is revisited after creating the session, a welcome message will be printed with the value of $_SESSION[‘name’].

session3.php

<?php

//Define the variable for checking valid login
$login = false;
//Start a session
session_start();

//Check whether the session is generated or not
if(!isset($_SESSION['name']))
{
   //Check the email or username is set or not
   if(isset($_POST['useremail']))
   {
      //Store the username or email and password after trimming
      $user = trim($_POST['useremail']);
      $password = trim($_POST['password']);
      //Check whether the submitted values are empty or not
      if($user != "" && $password != "")
    {
       //Read the content of the users.txt file
       $userfile = file("users.txt");
       //Read the file line by line
       foreach($userfile as $data)
       {
         //Read the data of the file in four variables after splitting based on comma(,)
         list($name, $email, $username, $pwd) = explode(",",$data);
         //Trim email, userame and password values
         $email = trim($email);
         $username = trim($username);
         $pwd = trim($pwd);
         //Authenticate the user based on username or email and password
         if(($username == $user || $email == $user) && ($pwd == $password))
         {
            //Store session data for the valid user
            $_SESSION['name']=$name;
            echo "<br /><h2 style='text-align:center'> You are logged in successfully.</h2>";
            $login = true;
            break;
         }
       }
    }
  }
  //Show the login form
  if ($login == false) include "loginForm.html";
}
else
{
  //Print the welcome message for the returning authenticated user
  echo "</br><h2 style='text-align:center'>Welcome back, ". $_SESSION['name']."</h2>";
}
?>

Output
The following output will appear after executing the above script the first time. The user has to type the valid username or email and password for the authentication.

The email address and the password have been provided in the following login form. These values will be matched by the email address and the password of each user of the file.

The following output will appear if the user presses the submit button after providing the valid email address and password. The same output will appear if the user provides a valid username in place of the email address for the authentication. The login form will appear again if an invalid username or email or password is provided by the user.

If the user reloads the same page again after successfully logging in, the following output will appear. The value of the $_SESSION[‘name’] variable has been printed here with the welcome message. This output will remain unchanged until the session expires for the user or the browser is re-opened.

Modify the Session Data

The session data can be modified after initializing the session variable. Create a PHP file with the following script to know the way of modifying the session variable after initializing the $_SESSION variable. The isset() function has been used in the script to check if the $_SESSION[‘visit’] variable is set or unset. If the $_SESSION[‘visit’] variable is not set then this variable will be initialized to 1. If the page refreshes or reloaded again then the value of this variable will be incremented by 1 for each refresh. The current value of this variable will be printed each time the page is loaded.

<?php
//Start the session
session_start();

//Check whether the session variable is set or unset
if (!isset($_SESSION['visit']))
    //Initialize the session variable
    $_SESSION['visit'] = 1;
else
    //Increment the session variable by 1
    $_SESSION['visit'] += 1;

//Print the current value of the session variable
echo "<h3> The page is visited for ". $_SESSION['visit']. " times </h3>";
?>

Output
The following output will appear after executing the above script for the first time. The value of the $_SESSION[‘visit’] is 1 here because when the page is loaded for the first time, this variable is initialized to 1.

The following output will appear if the page is loaded 3 times. The value of the $_SESSION[‘visit’] has been incremented by 1 each time the page reloads.

Delete the Session Data

The session data can be deleted by using unset() function or the session_unset() function of PHP. Create a PHP file with the following script that uses the unset() function to delete the session data. The $_SESSION[‘username’] variable has been initialized with a string value after starting the session. Next, the value of this variable has been printed before and after executing the unset() function for deleting the session data from the $_SESSION[‘username’] variable.

<?php
//Start the session
session_start();
 
//Set the session variable
$_SESSION['username'] = 'fahmidabd';

echo "Session data after set:<br />";

//Print the session variable after set
echo "Username :". $_SESSION['username']."<br />";
 
//Unset the session variable
unset($_SESSION['username']);

echo "Session data after unset:<br />";

//Print the session variable after unset
echo "Username :". $_SESSION['username'];

?>

Output
The following output will appear after executing the above script. The value of the $_SESSION[‘username’] has been printed before executing the unset() function and the $_SESSION[‘username’] variable became empty after executing unset() function.

Destroy the Session

The session information can be removed by unsetting the values of the $_SESSION variable that has been shown in the previous example. PHP has a built-in function named session_destroy() to delete all session related information completely. Create a PHP file with the following script that shows the use of the session_destroy() function. A form with a submit button has been used in the script to destroy the session. After starting a session, the isset() function has been used to check the “Destroy Session” button is pressed and the session ID is non-empty. The current session will be destroyed by calling the session_destroy() function if the session ID exists if the “Destroy Session” button is pressed by the user. If the page is visited for the first time and the “Destroy Session” button is not pressed then the session information will be stored in the $_SESSION[‘name’] variable. If the page is visited again after storing the session information but the “Destroy Session” button is not pressed then the welcome message will be printed.

<?php
//Start a new session
session_start();

if(isset($_POST['destroy']) && session_id() != "")
{
    //Destroy session
    session_destroy();
}
else
{
    if(!isset($_SESSION['name']))
    {
        echo "<br /><br />";
        echo "<h2 style='text-align:center'>New session has been started for the user.</h2>";
        //Save the session data
        $_SESSION["name"] = "Fahmida Yesmin";
    }
    else
    {
        echo "<br /><br />";
        //Read the session data
        echo '<h2 style="text-align:center">Welcome back, ' . $_SESSION["name"] . '.</h3>';
    }
    <div align="center">
    <form action="#" method="post">
        <input type="submit" name="destroy" value="Destroy Session" />
    </form>
    </div>

<?php
}

?>

Output
The following output will appear after executing the above script for the first time. If the user clicks on the “Destroy Session” button then the session will be destroyed completely and a blank page will appear.

Example 5: Encoding and Decoding Session Data

The session data can be encoded to generate a string value by serializing the data and the encoded session data can be converted into the array by deserializing the data. Create a PHP file with the following script that encodes the session data by using the session_encode() function and decodes the encoded session data by using the session_decode() function. According to the following script, the $_SESSION[“name”] and the $_SESSION[“email”] variables will be initialized with two values after starting the session. The values of these variables have been encoded by using the session_encode() function and printed later. The session_unset() function has been used to unset the $_SESSION variable. Next, the encoded string data has been converted into the array by using the session_decode() function.

<?php

//Start a new session
session_start();

echo "<h2>New session is generated.</h2>";

//Save the session data
$_SESSION["name"] = "Fahmida Yesmin";
$_SESSION["email"] = "[email protected]";
echo "The encoded Session Data is: <br>";

//Encode the session data
$encodedData= session_encode();
echo "Encoded session data:". $encodedData."<br><br>";

//Unset the session data
session_unset();

//decode the session data
session_decode($encodedData);
echo "Session data after decoding: ";

//Read the session data
echo '<h2>Welcome, ' . $_SESSION["name"] . '.</h3>';
?>

Output
The following output will appear after executing the above script. After encoding, the serialized session data has been printed in the output. According to the output, the pipe (|) and the colon (:) symbols have been embedded with the session data to create the encoded string and the length of each string value has been also included in the encoded string. Next, the encoded string has been decoded and the value of the $_SESSION[“name”] variable has been printed.

Conclusion

The session handling is a very important feature of any web-based application. PHP has many session handling directives and built-in session functions to handle session-related tasks. Some uses of commonly used session functions have been shown in this tutorial by using PHP scripts. The task of some session functions can be done by using the particular session directives. For example, if the session_auto_start directive is set to On then it will start the session automatically without using the session_start() function. Using a database table is an efficient way of storing the session data that is not covered in this tutorial. But the purpose of the session for the web application and the way of implementing the session handling feature using PHP script has been shown in this tutorial for helping new PHP users to add this feature in their application.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.