How to perform session timeout after 20 minutes using PHP?

One of the features people usually require while working on a back office panel for a system is that the user be automatically logged out if he has been idle for some time say 20 minutes i.e. implement session timeout in PHP.

This option was handled automatically in Classic ASP and Microsoft ASP.NET right now through the IIS (Internet Information Server). The session timeout is set to 20 minutes by default so you did not have to do anything over there except for checking whether the session value has become null and take appropriate action if it has.

Session timeout is the amount of idle time a user has spent while on the website. Once the amount of time surpasses the session timeout the web server clears the session variable and we know that the user is no more connected with the website.

This useful feature is not available through PHP or the web server by default so we will have to write our own code to make it work.

Following is the PHP code which does just that.

<?php
session_start();
$_SESSION['lasttime'] = null;
if ( $_SESSION['lasttime'] != '') {
$_SESSION['lasttime'] = time();
}
if ( (time() - $_SESSION['lasttime']) > 1200) {
// session expired. Reset session and direct to login page.
}

You will need to do one thing with the above code and that is to include it in every script at the top so that session timeout is verified at the start.

Hope the above helped. If you have any questions/comments then please let me know.