February 3, 2014 11:09 am

How to Check Expired Sessions using PHP & jQuery

This article can help you to check if a user’s session is expired or not if session expired show him popup or an alert window that your session is expired please login again. We need this feature for security reasons and its very useful and important for web developers who working on session based applications. We are using jQuery and PHP in this tutorial.

How to Check Expired Sessions using PHP & jQuery Ajax

jQuery Code snippet to check session

This jQuery trigger session_checking function every 10 second and if session expire it will show you a alert that your session expire please login again, if session available then nothing happen.

PHP Code to check session session.php

When ever this code execute it return a value 0 or 1, 0 means session expire and 1 means session not expire. We used login_time session where we put current time with time() function its a best practice to implement a session timeout on your own. in our condition we define that this session will work for 1 minute after one minute it will destroy session.

index.php file create session:

On page load we create this session with a login_time which counts set time of session creation and check after every 10 second if session expire reload page and create this session again.

I hope it helps you don’t forget to give us your reviews in comments.

Author Huzoor Bux

I am Huzoor Bux from Karachi (Pakistan). I have been working as a PHP Developer from last 5+ years, and its my passion to learn new things and implement them as a practice. Basically I am a PHP developer but now days exploring more in HTML5, CSS and jQuery libraries.

Tutorial Categories:
  • Nethawk

    As far as I understand it, there is a system defined session timeout in session.gc_maxlifetime. If in your script a very long timespan is defined (longer than the one in session.gc_maxlifetime) it will have no effect. I’d suggest for these cases to check session.gc_maxlifetime first and make sure, your timeout is under that limit. The PHP doc says the default for session.gc_maxlifetime is 1440 seconds (24 minutes).

  • Lester Oliver

    Thanks for this tutorial! i just wanted to do something more complex: How can i create a confirm box to renew the session if it has expired?