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.

View Demo download

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:

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.

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

insert a new line

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.

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 difference 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.

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.


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

16 thoughts on “Automatic session timeout/logout using php and AJAX : Part II”

  1. Hi,

    I tried this, great script, however is there anyway to make it work for all activity.

    For example, after integrating I tested and it still timed out and redirected if I was typing in a text field of clicked a button.

    Anyway help would great…

  2. i wouldnt recommend attempting to have the script run every time any action is taken on the page simply because it would put a tremendous load on the server. If you just set it to do the check every 10-15 minutes instead of every 10 seconds (which he only used for an example so you wouldnt have to wait 10 minutes to test it) it works fine. Theres absolutely no reason to check for activity every 10 seconds or any less than 10 minutes for that matter.

    On to my question. Im looking for a script similar to above that will also log out a user if they have had absolutely no activity on the page. IE: they left the page and went elsewhere (10 min later it marks them as logged off). Only reason i would like this is because my program ive been writting indicates the online users to all other users. Not sure if this can only be done server side. Thanks in advance

  3. @josh thanks for comment mate. Of course 1 second is just for an example. In live environment 10-15 minutes is good time. I have mentioned this in the post too.

    As for your question, this script will work fine.

    Did you see the demo . If you remain inactive in this page for 5 seconds it will log you out. You can change it to 10 minutes by setting 600000 (10*60*1000) in setInterval of javascript.

  4. When session expired i don’t want to see the page after Login directly when i copy paste the URL in the browser. Means when i get an alert and returned back to the main page unless and until i logged in again i don’t want to access the second page how can i achieve this

  5. First of all thanks this script/code is great and the explanation perfect. I was wondering though the best way to add a warning alert for the person that the page was going to expire if they do not have any activity. I tried modifying the code by adding a session warning variable and testing it against the difference variable but fir some reason the alert never showed.

  6. The thing is not working when there is any Javascript alert box or Confirm box exist on page and we keep the page on hold without closing that Alert/Confirm box.


  7. Incase user just closes the browser after logging in,how can i clean up the sessions in ths app or do i leave it to do that

Leave a Reply