PHP session is one of the methods for keeping data persistency 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.
This article contains sections that describe the PHP sessions, their time-limit configurations. It provides examples for setting session limits and tracking existence.
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.
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';
}
}
?>
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.
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.
This section describes the configuration directives used to set PHP session time. The below table shows two PHP.ini settings related to the session.
PHP directive | Description |
---|---|
session.gc_maxlifetime | It sets the max lifetime after which the session will be elapsed and collected as garbage. |
session.cookie_lifetime | It sets the time limit for the session cookie in seconds. Default is 0 which means to be persistent until the client quits. Note: PHP session_set_cookie_params() sets all the session cookie parameters in runtime. |
The below PHP info highlights the session configuration settings. Refer to more runtime session configuration directives in the linked official site.
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.
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>
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);
}
}
}
});
};
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();
?>
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.
Download
It’s great Information about sessions in Php. Php session provides a way to store web page visitor preferences on a web server in the form of variables that can be used across multiple pages. In Php session unset is just cleared out the session for usage.
Hi Harshal,
Thank you for adding value to the article.
Nice
Thank you Mihir.