A Guide to PHP Sessions

Sessions in PHP


Hello folks! welcome back to a new section of our tutorial on PHP. In this tutorial guide, we will be studying about Sessions in PHP.

An alternative way to make data accessible across different pages of an entire website is to use a PHP Session.

A PHP session creates a file in a temporary directory on the server where registered session variables and their values are stored. This data will be available to all the pages on the site during that visit.


The location of the temporary file is determined by a setting in the php.ini file called session.save_path. Before using any session variable, make sure you have setup this path.

When a session is started, following things occur -

  • PHP first creates a unique identifier for that particular session which is a random string of 32 HEX numbers.
  • A cookie known as PHPSESSID is automatically sent to the user's computer to store the unique session identification string.
  • A file is automatically created on the server in the designated temporary directory and bears the name of the unique identifier prefixed by sess_.

When a PHP script wants to fetch the value from a session variable, PHP automatically gets the unique identifier string from the PHPSESSID cookie and then looks in its temporary directory for the file bearing that name and a validation can be done by comparing both values.


A session ends when a user loses the web browser or leaves the website. The server is going to terminate the session after a fixed period of time, this is normally 30 minutes.

Starting a PHP Session

A PHP session is easily started by making a call to the session_start() function. This function first checks if a session is already started. If none is started, then it starts one. It is recommeded to put the call to the session_start() function at the beginning of the page.

Session variables are stored in associative array which is called $_SESSION[] and these variables can be accessed during lifetime of a session.

Example

The following example starts a session then registers a variable called counter that is incremented each time the web page is visited during session.

Make use of the isset() function to check if the session variable is already set or not.

Put this code in a test.php file and load this file many times to see the result -

<?php
   session_start();
   
   if( isset( $_SESSION['counter'] ) ) {
      $_SESSION['counter'] += 1;
   }else {
      $_SESSION['counter'] = 1;
   }
	
   $msg = "You have visited this page ".  $_SESSION['counter'];
   $msg .= "in this session.";
?>

<html>
   
   <head>
      <title>Setting up a PHP session</title>
   </head>
   
   <body>
      <?php  echo ( $msg ); ?>
   </body>
   
</html>

Output

When the above code is executed, it will produce the following result -

You have visited this page 1in this session.


Destroying a PHP Session

A PHP session can be destroyed by using session_destroy() function. This function does not require any argument and a single call can destroy all the session variables. If you want to destroy only a single session variable, then you can use unset() function to unset a session variable.

Example

Following below is an example to unset a single variable -

<?php
   unset($_SESSION['counter']);
?>

Following below is a function call which is going to destroy all the session variables -

<?php
   session_destroy();
?>

Turning on Auto Session

You do not need to call the start_session() function to start a session when a user pays a visit to your website if you can set session.auto_start variable to 1 in php.ini file.


Sessions without Cookies

There may be a case where a user does not allow storing of cookies on their machines. So there is another way to send session ID to the browser.

Alternatively you can use the constant SID which is defined if the session started. If the client does not send an appropriate session cookie, it has the form session_name=session_id. Else it expands to an empty string. Thus, you can unconditionally embed it into URLs.

Example

The following example illustrates how to register a variable, and how to link correctly to another web page using SID.

<?php
   session_start();
   
   if (isset($_SESSION['counter'])) {
      $_SESSION['counter'] = 1;
   }else {
      $_SESSION['counter']++;
   }
   
   $msg = "You have visited this page ".  $_SESSION['counter'];
   $msg .= "in this session.";
   
   echo ( $msg );
?>

<p>
   To continue  click following link <br />
   
   <a  href = "nextpage.php?<?php echo htmlspecialchars(SID); ?>">
</p>

Output

When the above code is executed, it will produce the following result -

You have visited this page 1in this session.
To continue click following link 

The htmlspecialchars() may be used when printing the SID, in order to prevent XSS related attacks.


Alright guys! This is where we are rounding up for this tutorial post. In our next tutorial post, we will be discussing about How to Send Emails using PHP.

Feel free to ask your questions where necessary and we will attend to them as soon as possible. If this tutorial was helpful to you, you can use the share button to share this tutorial.

Follow us on our various social media platforms to stay updated with our latest tutorials. You can also subscribe to our newsletter in order to get our tutorials delivered directly to your emails.

Thanks for reading and bye for now.