This question already has an answer here:
I have this code that logs a user out if they don't change pages for 10 minutes.
$inactive = 600;
if(isset($_SESSION['timeout']) ) {
$session_life = time() - $_SESSION['timeout'];
if($session_life > $inactive) {
header("Location: logout.php");
}
}
$_SESSION['timeout'] = time();
As you can see it's pretty straightforward. I include this function at the top of all my protected pages and if the script isn't run for 10 minutes, the next time you refresh the page, the user is sent to my logout script.
However that's the problem. After $session_life > $inactive becomes true, the script needs to be run again for the user to be logged out. I need the person to be immediately logged out as soon as this becomes true.
Is there any way to do this without things getting too complicated? (i.e. not using AJAX)
I've got an idea that I tested and it works on my server setup - it uses linux calls to set up a delayed removal of the session file. This is purely server-side and kills the session exactly when it should. You must have permissions to run shell commands though.
I'd include a meta refresh in the header of the page, and check how long it's been since the page was output. Some simple server side logic can accomplish that.
No. Your PHP code runs on every request. If you want the timeout to trigger "immediately" then you have to either spam the server with continuous requests (bad idea) or move the timeout logic to client-side code.
An appropriate solution could be to start a Javascript timer when the page loads and redirect the user to the logout page when the timer expires. If the user navigates to another page in the meantime the current timer would be discarded automatically and a new one started when that page loads. It can be as simple as this:
Update: Of course, you should also keep the server-side code to enforce the business rule on your own side. The Javascript will give you an "optimal" scenario when the client side cooperates; the PHP code will give you a guarantee if the client side works against you.
You can do it by subtrcting the current time say time(); to the time you want. try this link.
How do I expire a PHP session after 30 minutes?