Sunday, September 27, 2020

A Guide to PHP Sessions



Hello, dear readers! welcome back to another section of my tutorial on PHP. In this tutorial guide, we will be studying about Sessions in PHP.

An alternative way of making data accessible across all the 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 is going to 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 which is known as the session.save_path. Before making use of any session variable, make sure you have setup this path.

Whenever a session is started, the following things occur -

  • PHP first creates a unique identifier for that particular session which is a random string of 32 HEX numbers.
  • A cookie called PHPSESSID is automatically sent to the user's computer to store the unique session identification string.
  • A file is automatically built on the server in the selected temporary directory and as well 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 looks in its temporary directory for the file bearing that name and a validation can be done by comparing both values.


A session in PHP ends when a user loses the 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 no session 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 an 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 the below 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.

RECOMMENDED: A Guide to PHP Arrays

Destroying a PHP Session

A PHP session can be destroyed using session_destroy() function. This function does not require any argument and just 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 PHP start_session() function to start a session when a user pays a visit to your website if you can set the session.auto_start variable to 1 in php.ini file.

RECOMMENDED: PHP Logical Operators

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 make use of 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 shows 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 as well be used when printing the SID, to prevent XSS related attacks.

RECOMMENDED: PHP Static Variables

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

Feel free to ask your questions where necessary and i 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.
Share:

0 comments:

Post a Comment

Hello dear readers! Please kindly try your best to make sure your comments comply with our comment policy guidelines. You can visit our comment policy page to view these guidelines which are clearly stated. Thank you.