Working with Sessions in PHP

PHP Sessions

What is a PHP Session?
PHP session is a way of storing information in session variables, which could be used across multiple web pages for authentication. Unlike a cookie, the information is not stored on the user’s computer instead a session creates a file on the server, in a temporary directory, where it stores information in session variables. This stored information for a session will be available to all the web pages on the site during navigation. On the server, the location of a temporary file is determined by a setting in the php.ini file called session.save_path.

PHP session when created, it involves the following three steps:

  • When a session is created, PHP generates a unique session identifier, which is a random string of 32 hexadecimal numbers. A session id resembles somethinglike this 9c8foj87c3jj973actop1re472e8774.
  • Server sends a cookie known as PHPSESSID to the user’s machine to store unique session identification string.
  • The Server will generate a file in a designated temporary directory that has the name of the unique session identifier prefixed by sess _g.  sess_9c8foj87c3jj973actop1re472e8774.

This set up helps PHP script to retrieve the session variable values from a file. On client side PHPSESSID cookie has the session identifier which confirms the file name to look up in designated directory at the server side where session variables could be retrieved and used for validation. A user can end a session by hitting the website’s logout button which executes the session_destroy () function. Also, when user closes the browser, the PHP session gets terminated automatically. Otherwise, the server will terminate the session after a predetermined time period.

Session Syntax in PHP
A PHP session is created with the session_start () function and is destroyed with the session_destroy () function. A PHP global variable, known as $_SESSION, is used to set values to session variables. We can unset all values set to session variables using the session_unset () function.

SYNTAX DESCRIPTION
session_start(); It is an in-built function used to create a PHP session.
session_destroy(); It is an in-built function used to destroy a PHP session.
session_unset(); It is an in-built function used to unset all session variables. It is triggered before the session_destroy () function.
isset (); It is an in-built function to check if session variable is already set or not.
$_SESSION It is a PHP global variable that is used to set values to Session variables. E.g. $_SESSION[“userID”] = “php_user”;
print_r($_SESSION) It will print the complete array of the session variables and their values.

Session Operations

We are be going to do the following operations using PHP session with examples.

  • Start a PHP Session and set Session Variables: A new PHP session starts with the session_start () function. Once a session is created, then we can set values for the session variables using the PHP global variable: $_SESSION as shown below. Here, we have set the values for the session variables “userID” as “php_user” and “password” as “tutorials”.
<?php
// Start the PHP session
session_start();
?>
<!DOCTYPE html>
<html>
   <head>
      <title>PHP Session - Create</title>
   </head>
<body>
<?php
// Set session variables
$_SESSION["userID"] = "php_user";
$_SESSION["password"] = "tutorials";
echo "<br>PHP Session is established and session variables are set successfully!";
?>
</body>
</html>

Output: When we run above PHP code on the web server, it will display the below output.

PHP Session is established and session variables are set successfully!

  • Retrieve PHP Session Variables values: We can retrieve the values of the session variables that we set last time after creating PHP session. When we open PHP session at the beginning of each page (session_start ()) should be written as shown below. Here, we are retrieving and echoing those values using the global $_SESSION variable.
<?php
// Start the PHP session
session_start();
?>
<!DOCTYPE html>
<html>
   <head>
      <title>PHP Session - Retrieve</title>
   </head>
<body>
<?php
// Echo PHP session variables that were set before on previous page
echo "User ID is " . $_SESSION["userID"] . ".<br><br>";
echo "Password is " . $_SESSION["password"] . ".";
?>
</body>
</html>

Output: When we run above PHP code on the web server, it will display the below output. In the output, we can observe the values of the session variable, that we have set earlier after PHP session creation.

User ID is php_user.
Password is tutorials.

  • Update PHP Session Variables values: We can update the values of the session variables in the same session by overwriting the existing values of those variables as shown below. As explained earlier, before we start updating the values of the session variables, we need to open a PHP session at the beginning of each page (session_start ()). Here, we have updated the values for the session variables “userID” as “new_php_user” and “password” as “education”.

We can print the complete array of session variable and their values by using the print_r ($_SESSION) function as shown below.

<?php
// Start the PHP session
session_start();
?>
<!DOCTYPE html>
<html>
   <head>
      <title>PHP Session - Modify</title>
   </head>
<body>
<?php
// Set PHP session variables
$_SESSION["userID"] = "new_php_user";
$_SESSION["password"] = "education";
echo "PHP Session variables are modified successfully!<br><br>";
print_r($_SESSION);
?>
</body>
</html>

Output: When we run the above PHP code on the web server, it will display below output. In the output, we can observe the array of the session variables with their values which is modified and has different values for the respective session variables.

PHP Session variables are modified successfully!
Array ([userID]=>new_php_user[password]=>education)

  • Destroy a PHP Session and unset all Session Variables values: Lastly, we can unset the values for all the PHP session variables by using the session_unset () function and destroy the current session using the session_destroy () function of PHP as shown below.
<?php
// Start the PHP session
session_start();
?>
<!DOCTYPE html>
<html>
   <head>
      <title>PHP Session - Destroy</title>
   </head>
<body>
<?php
// remove all PHP session variables
session_unset();
print_r($_SESSION);
// destroy the PHP session
session_destroy();
echo "<br><br>PHP Session is destroyed successfully and all session variables are removed!<br><br>";
?>
</body>
</html>

Output: When we run above PHP code on the web server, it will display the below output. In the output we can observe that session array is blank after we used session_unset () function.

Array()
PHP Session is destroyed successfully and all session variables are removed!

Conclusion:
In this chapter, you have learnt about various PHP Session functions, their syntaxes and various operations such as starting a PHP Session, retrieval of values from Session variables, modification of values for those variables and destroying a PHP Session completely. Unlike Cookies, here the information is stored at the server side. Therefore, a PHP sessions is more secured and not prone to security attacks and client state data inconsistencies.

Good Luck 🙂

Leave a reply:

Your email address will not be published.