Automatic session timeout/logout using php and AJAX : Part II

This article is final part of 2 part series in which you will learn how to logout a user after a specific amount of inactivity. In part 1, we used only php. In this part, we will extend this functionality and will use AJAX to automatically logout the user if the inactivity time is exceeded. Logout will be irrespective of whether the user requests any page from server or not.
Understanding part 1 is necessary to complete part 2. You can read it here.

Hope you enjoyed the last post. In last post you saw that we logged out the user if she requests a page from the server after certain inactivity period.
Would it not be better that if the application ended the session as soon as the timeout period expires without having to wait for the user to request the page again. Sure it would be and this is what you will learn in this article.

A demo can be seen here and complete source code is available for download here
So get ready now.

We will poll the server with AJAX to check if the timeout period has passed or not. The response of AJAX call will have a boolean value by which we will redirect the user. I will assume that you have working knowledge of AJAX and therefore will not explain the AJAX code in detail.

Here are the steps that we will follow:

1- Set a poller in javascript that will contact a php script in our example.
2- The php script will check the timeout status of user.
3- php script will return either true or false as AJAX response depending upon if the session is timed out or not.
4- Response true means timeout has expired, hence user will be redirected to home page whereas false means user is still logged in.

Let’s do it in code now.
First the javascript part.Create a file named ajax.js in the same directory where other files are placed with this code:

window.onload = init;
var interval;
function init()
{
	interval = setInterval(trackLogin,1000);
}
function trackLogin()
{
	var xmlReq = false;
	try {
	xmlReq = new ActiveXObject("Msxml2.XMLHTTP");
	} catch (e) {
	try {
	xmlReq = new ActiveXObject("Microsoft.XMLHTTP");
	} catch (e2) {
	xmlReq = false;
	}
	}
	if (!xmlReq && typeof XMLHttpRequest != 'undefined') {
	xmlReq = new XMLHttpRequest();
	}
 
	xmlReq.open('get', 'check.php', true);
	xmlReq.setRequestHeader("Connection", "close");
	xmlReq.send(null);
	xmlReq.onreadystatechange = function(){
		if(xmlReq.readyState == 4 && xmlReq.status==200) {
			if(xmlReq.responseText == "true")
			{
				clearInterval(interval);
				alert('You have been logged out.You will now be redirected to home page.');
				document.location.href = "index.html";
			}
		}
	}
}

Line 1 says, execute the init function after the DOM is loaded. Then we declare a variable interval. In init we use setInterval function. setInterval executes the function name passed as first parameter every number of milliseconds specified as second argument. In this case trackLogin will periodically execute after 1000 ms or 1 second. Keeping time limit this much low is not advisable as this will put too much load on servers. It must be somethingh like 5 to 10 minutes depending upon the requirement of the application.

Now we come to trackLogin. This is the function which will make an AJAX call to our php script.
Lines 9 till 21 create an instance of XMLHTTP object.
Line 23 opens a connection to the check.php file on the server using get method.
In line 26 we register the callback function i.e. when ajax call returns from the server.
Line 28 checks whether the response is true. true means user has been logged out on the server and thus will have to login again. Therefore, in line 30 we remove the polling by using clearinterval and redirect the user to homepage after informing that session has been terminated. No action is taken in case response is false.

This makes our javascript/AJAX part over. Moving to php now, there are some changes in php files also.
Open the file first.php and go to the function showLoggedIn. Paste this line between declarations.

echo'<script src="ajax.js" type="text/javascript"><!--mce:0--></script>';

Do the same for second.php.

checkIfTimedOut function has also been moved to a separate file called ‘timeCheck.php’ since it will be used in 3 places now. So, delete the function definition for checkIfTimedOut from both these files and just before the line

$hasSessionExpired = checkIfTimedOut();

insert a new line

require 'timeCheck.php';

Now create another file called check.php(that we called through our polling function in javascript).
Here we will write a function timeCheck which will determine whether session ended or not. It will return true if timeOut has been exceeded,false otherwise.

function timeCheck()
{
    if(!isset($_SESSION['isLoggedIn']) || !($_SESSION['isLoggedIn']))
    {
		//user is not logged in
	    session_unset();
	    return true;
	    exit;
    }
	else
	{
		// user is logged in
		require 'timeCheck.php';
		$hasSessionExpired = checkIfTimedOut();
		if($hasSessionExpired)
		{
			session_unset();
			return true;
		}
		else
		{
			return false;
		}
	}
}

In line 3 we check if the user is logged in or not. If not then session_unset is called and we return true.
If the user is logged in control goes to line 13.
Here we include the file timeCheck.php which contains the definition for checkIfTimedOut. In the next line we call checkIfTimedOut(). As you know from previous post, this function calculates the differnece between current time and last accessed time(which is stored in session variable loggedAt) and returns true if the difference is greater then the session variable timeOut.
If it returned true, we unset all session variables and return true.

Now add these lines to the file where we will call timeCheck function.

session_start();
$stillLoggedIn = timeCheck();
echo $stillLoggedIn;

Pretty simple, AJAX call will arrive at this page every second.And timeCheck() will be called each time.
Value of $stillLoggedIn will be returned as the response to the AJAX call.

That is all we have to do.

Now open the index.html in your browser and click on Login. This will log you in and take you to first.php. Stay inactive here for more than 5 seconds and you will see the alert that you have been logged out. Try the same for second.php.
If you keep on navigating between first.php and second.php in less then 5 seconds, your session will not end. Try changing the timeOut specified in first.php.
If you are on firefox and have firebug installed, you can see in the console that every second an AJAX call is being made to page.

Download source code

That brings us to the end of this 2 part series. Hope you enjoyed it. If you have any questions or would like me to explain the code further, I will be most happy to do so. Please leave a comment or stumble the page if you liked this article.

Related Posts

ajax, javascript, php

If you enjoyed this post, please consider to leave a comment or subscribe to the feed and get future articles delivered to your feed reader.

Comments

5 Responses to “Automatic session timeout/logout using php and AJAX : Part II”

Leave Comment

(required)

(required)


9,518 spam comments
blocked by
Akismet