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.

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.

Checking for expired PHP sessions

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 – 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

If you enjoyed this article, Get email updates (It’s Free)
http://w3lessons.info/wp-content/uploads/2014/01/Session-Expires-PHP.pnghttp://w3lessons.info/wp-content/uploads/2014/01/Session-Expires-PHP-150x150.pngKarthikeyan KjqueryPHPnew techniques,php
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.I have used javascript timing event -  setInterval() - executes a function, over and...