PHP Session TimeOut Login Popup with jQuery & Ajax

My readers are asking that how do we display message to users that their sessions got expired. So I thought this tutorial will really useful to lots of web developer who working on session based websites. We should always notify our users that their PHP session timeout via popup or alert box. In this example, we are going to show timeout alert in a popup

I have used javascript timing event –  setInterval() – executes a function, over and over again, at specified time intervals

The setInterval() method will wait a specified number of milliseconds, and then execute a specified function, and it will continue to execute the function, once at every given time-interval.

php session timeout login popup with ajax login

Tutorials you may also like

jQuery Code – executes every 5 seconds

var check_session;
function CheckForSession() {
var str="chksession=true";
jQuery.ajax({
type: "POST",
url: "chk_session.php",
data: str,
cache: false,
success: function(res){
if(res == "1") {
alert('Your session has been expired!');
}
}
});
}
check_session = setInterval(CheckForSession, 5000);

In the above javascript function called CheckForSession(), it will called every 5 seconds to check the sessions via chk_session.php

PHP code to check session timeout – chk_session.php

session_start();
$name = $_SESSION["w3name"];
if($name == '')
{
//session expired
echo "1";
} else {
//session not expired
echo "0";
}

If sessions are empty then the response will be “1”.

I hope you will like this tutorial. You can use this code in your live projects.

Please don’t forget to share and subscribe to latest updates of the blog. Comments and feedbacks are always welcome!

Thanks!

View Live Demo Download

You May Also Like

Never Miss Any Web Tutorials, Guides, Tips and Free eBooks

Join Our Community Of 50,000+ Web Lovers and get a weekly newsletter in your inbox

 

I hate spam too. Unsubscribe at any time.

11 thoughts on “PHP Session TimeOut Login Popup with jQuery & Ajax”

  1. Arem’t you risking a nasty error message if the session has indeed expired and the noted session key no longer exists? Shouldn’t ‘array_key_exists()’ be used here?

    Reply
    • Very true! I have been thinking this over myself. As soon as you make a server-side call (ajax) the session would refresh automatically. This is a ‘keep alive’ method and not ‘session expiry detection’. I need a method to detect session expiry.

      Reply
  2. you can prevent the alert box only one time rather to each 5 sec. and the best way is to use local-storage rather then ajax , in this you are always contacting to the server this is not a good.

    Reply

Leave a Comment