Skip to content

How to set and unset session in PHP?

  • by
php session

This article contains sections that describe the PHP sessions (set and unset session), their time-limit configurations. It provides examples for setting session limits and tracking existence.

PHP session is one of the methods for keeping data persistence on the server side.

PHP sessions have a deadline time limit for keeping data persistent. PHP configuration file includes directives to have this specification.

We can also create custom code to change the default PHP session deadline.

The below example gives a quick solution to set PHP session time. It contains only two steps to set and track the session expiration status.

Quick example

1. Create a file set-session.php and set value and lifetime.

<?php
session_start();
//Set PHP session with value, time
$currentTime = time();
$_SESSION['color'] = array(
    "value" => "blue",
    "time" => $currentTime,
    "life_time" => 5
);
?>

2. Create a file check-session.php to compute if the session existence.

<?php
session_start();
if (isset($_SESSION['color'])) {
   $sessionSetTime = $_SESSION['color']['time'];
   $sessionLifeTime = $_SESSION['color']['life_time'];
   if ((time() - $sessionSetTime) > $sessionLifeTime) {
        unset($_SESSION['color']);
        print 'Session expired';
    }
}
?>

About PHP session

We have already seen PHP sessions and cookies in a previous article. PHP sessions are for managing application data, state persistent during the working flow.

There are a lot of uses of sessions in an application. The below list shows some of the states or data managed by the use of sessions.

  • Managing  shopping cart in session
  • Keeping user logged-in state in session.
  • Store the User-selected language in session in a multi-lingual website.

We have seen how to create a login script using the PHP session. In that, the session lifetime tracking can be used to log out after few minutes of inactivity.

Example: Working with PHP session time – Set expiration and limit lifetime

This PHP session time handling example is the enhanced version of the above quick example.

It creates three session variables to set color, shape and size. It sets the lifetime for each PHP session variable while setting values.

The PHP code checks if the session exists. Once the time is reached, it unset that particular session variable and destroys it.

Landing page to set session

The landing page of this example shows a control to set the PHP session time. Once started, the session expiration status is checked at a periodic interval. This page includes the AJAX script to raise the call to PHP to check the session.

If the PHP session time is over, then this page will display a notice to the user. After all the sessions are expired, then the page will clear the notification and ask to reset the session.

index.php

<html>
<head>
<link href="./assets/css/style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="session"
	data-status='<?php if(!empty($_GET["status"])) { echo $_GET["status"]; } ?>'>
  <div id="box">
    <h1 align="center">Set PHP session time</h1>
    <div class="text"> <a href="set-session.php" class="btn">Reset Session</a> </div>
    <div id="status"></div>
  </div>
  <div id="message"></div>
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="./assets/js/session.js"></script>
</body>
</html>

Check PHP session time via JavaScript AJAX

This script sets an interval to

call the AJAX script to check the PHP session time. After getting the response, this AJAX success block shows the expired PHP sessions.

It checks the PHP session time every 5 seconds via AJAX. This script uses JavaScript setInterval() to invoke the checkSession() method.

session.js

if($('.session').data('status') != "") {
    var interval;
    interval=setInterval(checkSession, 5000);
    $("#status").text("Checking session expiration status...");
}
function checkSession(){
    $.ajax({
        url:"check-session.php",
        method:"POST",
        success:function(response){
            if(response!=""){
                if(response == -1){
                    $("#status").hide();
                    clearInterval(interval);
                    window.location.href='index.php';
                }
    	        else{
                    $("#message").append(response);
                }
            }
       }
    });
};

Set unset PHP session time

In this section, it shows two PHP files to set and unset the PHP session time.

The set-session.php is called on clicking the UI control on the landing page. It sets the color, shape and size in the PHP session.

Each session array is a multi-dimensional associative array. It has the details of PHP session set time, lifetime and value.

The session set-time and lifetime are used to calculate the session expiry.

set-session.php

<?php
if (! isset($_SESSION)) {
    session_start();
}
$currentTime = time();
$_SESSION['color'] = array(
    "value" => "blue",
    "time" => $currentTime,
    "lifetime" => 3
);
$_SESSION['shape'] = array(
    "value" => "circle",
    "time" => $currentTime,
    "lifetime" => 5
);
$_SESSION['size'] = array(
    "value" => "big",
    "time" => $currentTime,
    "lifetime" => 10
);
header("Location: index.php?status=starts");
exit();
?>

This code returns the response text once the session is expired.

It validates the session expiry by comparing the remaining time and the PHP session lifetime.

Once all three sessions are expired, then this code returns -1. On receiving -1, the AJAX callback stops tracking by clearing the interval.

check-session.php

<?php
if (! isset($_SESSION)) {
    session_start();
}

if (! isset($_SESSION['color']) && (! isset($_SESSION['shape'])) && (! isset($_SESSION['size']))) {
    print - 1;
}
if (isset($_SESSION['color'])) {
    $sessionTimeColor = $_SESSION['color']['time'];
    $sessionLifeTimeColor = $_SESSION['color']['lifetime'];
    if ((time() - $sessionTimeColor) > $sessionLifeTimeColor) {
        unset($_SESSION['color']);
        print '<div class="response-text"><span>Color Session Expired</span></div>';
    } 
}

if (isset($_SESSION['shape'])) {
    $sessionTimeShape = $_SESSION['shape']['time'];
    $sessionLifeTimeShape = $_SESSION['shape']['lifetime'];
    if ((time() - $sessionTimeShape) > $sessionLifeTimeShape) {
        unset($_SESSION['shape']);
        print '<div class="response-text"><span>Shape Session Expired</span></div>';
    } 
}

if (isset($_SESSION['size'])) {
    $sessionTimeSize = $_SESSION['size']['time'];
    $sessionLifeTimeSize = $_SESSION['size']['lifetime'];
    if ((time() - $sessionTimeSize) > $sessionLifeTimeSize) {
        unset($_SESSION['size']);
        print '<div class="response-text"><span>Size Session Expired</span></div>';
    }
}
exit();
?>

Conclusion

Thus we have learned how to set PHP session time via programming. This article described the PHP configurations to set max session lifetime.

I hope this example helped to create your own code to manage PHP sessions and time.

Leave a Reply

Your email address will not be published. Required fields are marked *