How to increase PHP session timeout?

Table of Contents What is a PHP Session?How does the PHP session work?How to create session in PHP?Conclusion What is a PHP Session? It is a method that is used to store information across different …

Session timeout PHP

What is a PHP Session?

It is a method that is used to store information across different pages. The session creates a temporary file that stores the user information in variables in the server and client computer, unlike cookie that stores user information on the user computer. 

When we use websites, the webserver stores our information in variables by using Session parameters that are accessible by multiple pages at the same website. The session starts before opening the HTML file when the user opens a website and removes all the information when the user closes the website.

How does the PHP session work?

Suppose You have logged in to Instagram and try to reach/navigate on a particular page of Instagram. You just write the name of the page in the search bar of Instagram, click, and visit that page without any authentication. Here a session that will allow you to go to a page without authenticating yourself or login in again. You can visit different pages with the help of a session without login in again on the same application.

How to create session in PHP?

Although a PHP Session is temporary user data that is stored for multiple pages, it stores information and removes it when the user closes the browser, but you can increase PHP session time with the help of different functions.

When we create a session, it is necessary to write session_start() on the top of the file. We cannot write it at the end of the file because the session gets information on variables when the file starts.

Start a session with

session_start();

Define global variable inside the session:

$email = “[email protected]” 
$_SESSION['email’] = $email;

session.gc_maxlifetime: It is responsible for the time that an inactive session will not expire for how much time. This is by default 1440 seconds or (24 * 60) to expire a session if the user is not active or not even making a click on the website. Suppose a user is using the website for a long time without going inactive or user inactive time does not increase then the default time, the user will not log out.

Here is an example of a how-to increase session timeout in PHP.

In this article, we have created a simple login/logout page that is connected with the SQL database. 

First, we will create a MySQL database “drasticcode” that stores a login table with a username and password with a unique id.

CREATE TABLE `login` (
  `id` int(100) NOT NULL,
  `username` varchar(255) NOT NULL,
  `password` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

Insert data into the table

INSERT INTO `login` (`id`, `username`, `password`) VALUES
(1, 'admin', 'admin123');

After creating the database, we will create a login page and then connect it with the database.

These are the PHP files that we are going to create in this PHP Session timeout example.

Create an index.php file that designs the interface of the login page with the help of HTML and CSS. This page contains the username and password attributes with a login button inside the form tag.

<html>  
<head>  
    <title>PHP login system</title>  
    <style type="text/css">
#frm{  
    border: solid gray 1px;  
    width:25%;  
    border-radius: 2px;  
    margin: 120px auto;  
    background: white;  
    padding: 50px;  
}  
#btn{  
    color: #fff;  
    background: #337ab7;  
    padding: 7px;  
    margin-left: 70%;  
}  
    </style>     
</head>  
<body>  
    <div id = "frm">  
        <h1>Login</h1>  
        <form action = "login.php" method = "post">  
            <p>  
                <label> Username </label>  
                <input type = "text" id ="user" name = "user" />  
            </p>  
            <p>  
                <label> Password </label>  
                <input type = "password" id ="pass" name = "pass" />  
            </p>  
            <p>     
                <input type = "submit" name='login' id = "btn" value = "Login" />  
            </p>  
        </form>  
    </div>  
</body>     
</html>   

You will get the screen of the login page.

session timeout PHP

Create a connection.php file that connects the login page with the database

<?php      
      function connect(){
    $con = mysqli_connect("localhost", "root", "", "drasticcode",3306);    
    if($con) {
        return($con);
    }
    else {
        return null;
    }
}
?>  

Now add a PHP session on every page of login activity. To add PHP session time, we first start the session. Create a welcome_user.php page that will open when the user enters the right username and password.

<?php
    $user=$_SESSION['user'];
    $username=$user['username'];
    $pass=$user['password'];
    echo "<h1>".'Welcome '.$username;
} 
else{
    header('Location: index.php');
}
?>
<html>
<form action= "logout.php">
    <br><input type="submit" name="Logout" value="Logout">
</form>
</html>
session timeout PHP

This is the logout.php file that destroys the session when the user clicks the logout button and navigates to the index page that is a user login page.

<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
    session_destroy();
    header('Location:index.php');
?>

And display the output when the username or password is invalid

session timeout PHP

This is a simple login/logout activity in which we have used a PHP session that helps to navigate from one page to another. But what if the admin wants that page to save the session for a longer time than the default time because of many reasons. It may be that refreshing after every 24 min makes users annoyed to lose their login information again and again. It may be that the page is not needed to refresh if it does not contain any restricted information. To handle this issue, we use some built-in function of PHP session time that works in real-time and logout session when PHP session timeout.

  • After the session starts, include a connection.php file that helps to connect the database with the login page.
  • Get username and password from the login page and match it with data that is inserted in the database.
  • The session is created when both database and input username and password are matched.
  • session_start() does two things, it creates a temporary file on the server of which to store session data, and also sends a cookie to the user’s browser. This cookie has a default expiration time, so calling session_set_cookie_params(seconds) will change the default expiration time of the cookie to what you define. The cookie points the client to their session, so it is required to access the session.
  • With session_set_cookie_params() you can define the cookie options (like lifetime, etc.). If a session gets started these values are used for the cookie that is sent to the client. The cookie however is sent only at the beginning of the session but not for any further requests from the client. This means that the cookie with being removed by the client after [session start time] + [session timeout] has been reached. Effectively you define a max lifetime of a session.
  • session_set_cookie_params() means select the parameters that we use to set cookie it may be our username, or something else
<?php
session_start();
//this is login file where session created after matching the correct information 
    include('connection.php');  
    if(isset($_POST['login'])){
        $username = $_POST['user'];  
        $password = $_POST['pass']; 
        
        $con=connect();
        if($con){
            $query="SELECT * FROM `login` ";
            $result=mysqli_query($con,$query);
            if($result){
          while($row=mysqli_fetch_assoc($result)){
            //   print_r($row);
           if($row['username']==$username && $row['password']==$password){
               /*if database username field match your input username and password then it creates session*/	
                ini_set('session.gc_maxlifetime', 172800);
                session_set_cookie_params(172800); 
               
                $startingtime = time();
                $_SESSION['expiry'] = $startingtime + (2880 * 60);	
               
            $_SESSION['user']=$row;   // create session
            echo "login sucsessfully";
           header('Location:welcome_user.php');
        //    move to welcome file //   
    }
       else{
            echo "<h3>Invalid Username or Password</h3>"; 
            break;
        }}
    }
    }
}
?>

Add this session at the start of the welcome_user.php code. After the session starts, it will log in the inactive user until the session expiration time decreases than the original time. Suppose we set PHP session timeout or session expiration time for an inactive user is 48 hours. Here gettime() is the real-time function that will start to count the time when the session starts and destroy when gettime increases then expires time such as 48.00.01 and the user automatically logout. To login again, the user needs to enter a username and password.

<?php
session_start();

/* get information if session is not empty*/
if(isset($_SESSION['user'])){
    //or if(!empty($_SESSION['user'])){
        $getTime = time();
        if($getTime > $_SESSION['expiry']) {
          session_destroy();
          header('location:logout.php');
        }
       ?>

Conclusion

This article helps you to create a PHP session time and how to increase the PHP session timeout. We create a login/logout page that has 48 hours of time duration to log out an inactive user with the help of the PHP session timeout function.

Suggested Read: OpenCV VS Tensorflow

Categories PHP

Leave a Comment