Web Programming TutorialsLearn Working with Sessions in PHP

Learn Working with Sessions in PHP

Working-with-Sessions-in-PHP

Introduction to Session
You might have multiple accounts on numerous websites such as online shopping, social media, professional network, etc.  While logging in to these dynamic websites, you need to enter your required details including username, password, location, etc. which creates a session at the server. If you leave the website idle for a long time without conducting any action on it, you will see that the moment you try to click on a link or any button on that website, it will show you the following message ‘session expired’ and you are logged out forcefully. After that, the system asks you to re-authenticate yourself and re-enter your login details. Unlike your personal computer, which has all the required details, the server is a stateless system and the HTTP address doesn’t maintain state so it does not remember your state or details. Therefore, you setup a session through system login after giving the required details to the server. Using those details, the server identifies you and let you perform required operations like changing information across various web pages, adding new details, etc. Once you have completed your work on the website, you destroy your current session by clicking the log out button, which ensures that your session details are forgotten completely by the web server.

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.
1

  • 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.
2

  • 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.
3

  • 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.
4

Conclusion:
In this chapter, we 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.

3 COMMENTS

  1. Nice tutorial I have not been familiar with this…
    I have a bit silly question….
    Does the session variable which is declared in one php file remains available in other file untill the session close function….

    I have been trying to do so in my login page for website…..!!!!

    • Yes, just remember to use session_start() at the beginning of the files and you will be able to use the session variables between the two pages. Hope this helps!

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -