Last Updated On By Khizer Ali
In this article, we will explain how to increase session timeout in PHP but firstly it’s important to know that what are session?
In PHP, sessions are maintained to check if the user is active or not. When you work on an application, you open it and do some changes and then close it. This duration is called a session.
When you log in to any of the websites, a new session is created with a unique session ID. It will maintain all the record of your activities which you perform on the site while logged in.
By default, the PHP session expired when you close the browser or after a specific time. That usually is 24 minutes, but it depends on your server configuration. You can manually increase session timeout in PHP according to your scenario if you follow the steps which you are going to learn in this article.
First, I’m going to briefly explain the three steps which involve to starting a session till session destroy.
Table of Contents
session_start() is used to start a PHP session or resume the current one in the web page. It generates a unique session ID for the user.
session_start();
After the start of the session, session variables can be created for future use. It can be accessed throughout the application. You can create a session variable and store value in it with the following syntax:
$_SESSION['userName'] = "CodeLeaks";
We need to destroy the PHP session when a user logs out from the web site. To free all the session variable, the following command is used.
session_unset();
To end the complete session, following command is used.
session_destroy();
<?php
// server should keep session data for AT LEAST 1 hour
ini_set('session.gc_maxlifetime', 3600);
// each client should remember their session id for EXACTLY 1 hour
session_set_cookie_params(3600);
We’ve already discussed the basic functions used for handling a session. Now, come towards the main part, which is How to increase the session timeout in PHP.
Let’s take a simple example of a login form, from which a user can log in to their account. For this, we have our database in phpMyAdmin with the name “authentication”. In this database, we have a table called “users” which has the list of all registered user names and their password.
First, we need to establish our connection with the database.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "authentication";
// create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
if ($conn) {
# code...
// echo "Connecton Open";
}
else
echo "Connection failed";
?>
Our main file is index.php, having a simple login form. User has to enter his/her credential to be able to access the home page of the Web site.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap
/4.4.1/css/bootstrap.min.css" integrity="sha384 Vkoo8x4CGsO3+Hhxv8T
/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<link rel="stylesheet" href="index.css">
<title>Log in</title>
</head>
<body>
<div class="wrapper mx-auto mt-5">
<h2 class="text-center mb-4">LOG IN</h2>
<form method="POST" action="">
<div class="row">
<div class="col-12">
<input type="text" class="form control" placeholder="User Name"
name="username" required>
</div>
<div class="col-12 mt-3">
<input type="password" class="form-control" placeholder="Password"
name="password" required>
</div>
</div>
<input type="submit" name="login" class="btn btn-secondary mt-4 w-100
login-btn" value="Log In" >
</form>
</div>
</body>
</html>
When a user clicks on Log In button, credentials are matched with our database record to find whether the user is registered or not.
If the user’s information matches then, session starts and session variables are set. A session variable $_SESSION[‘start’] is initialized to store the time of login. Another variable $_SESSION[‘expire’] calculates the time which we’ll use to destroy our session.
Here we multiply our 40 minutes with 60 to convert them into seconds (You can change the value 40 minutes as per your requirement). It is then directed to the home page of the web site.
<?php
include("connection.php");
error_reporting(0);
if($_POST['login']) {
$un=$_POST['username'];
$pass=$_POST['password'];
$query = "SELECT * FROM USERS WHERE user_name='$un' AND password='$pass'";
$data = mysqli_query($conn,$query);
$total = mysqli_num_rows($data);
if($total != 0) {
session_start();
$_SESSION['auth'] = true;
$_SESSION['start'] = time();
$_SESSION['expire'] = $_SESSION['start'] + (40 * 60);
header('location:homePage.php');
echo "run";
} else {
?>
<script>
alert("user name or password is invalid");
</script>
<?php
}
}
On the home page, the session_start() function is called to maintain the session. It allows us to fetch session variables from the page. An if() statement is maintained to check that someone is not directly trying to access the page without login. If this is the case, then the URL will automatically redirect to the Log in page.
If the user is already logged in, then the current time is stored in a variable $currentTime. The current time shouldn’t exceed the desired timeout which we calculated previously in “index.php” page. When the duration exceeds the session is destroyed, and it is redirected to the Log in page.
<?php
include("connection.php");
error_reporting(0);
session_start();
if(!$_SESSION['auth']) {
header('location:index.php');
}
else {
$currentTime = time();
if($currentTime > $_SESSION['expire']) {
session_unset();
session_destroy();
header('location:index.php');
}
else {
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4
.4.1/css/bootstrap.min.css" integrity="sha384Vkoo8x4CGsO3+Hhxv8T/Q5Pa
XtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<link rel="stylesheet" href="index.css">
<title>Home Page</title>
</head>
<body>
<div class="row no-gutters d-flex justify-content-end pr-3">
<a href="logout.php" class="logout">
<input type="submit" name="login" class="btn btn-secondary mt-3"
value="Log Out">
</a>
</div>
<h1 class="text-center">Welcome to the Home Page</h1>
</body>
<?php
}
}
?>
</html>
Below is the PHP logout script which is used if anyone wants to log out from the page before the session timeout.
<?php
session_start();
session_unset();
session_destroy();
header('location:index.php');
?>
Creating a session in PHP is considered to be a fundamental element in a website. In today’s world, almost every site has a system to authenticate its user, and there could be different scenarios where the owner of the website wants to create a PHP session for a specific period. In this article, we have seen how to increase session timeout in PHP.