session timeout due to inactivity
php
Solution
If you want to logout the user if they try to load a page when they've been inactive for too long, you should put this code at the top of every php file (before ANY other html tags):
if( $_SESSION['last_activity'] < time()-$_SESSION['expire_time'] ) { //have we expired?
//redirect to logout.php
header('Location: http://yoursite.com/logout.php'); //change yoursite.com to the name of you site!!
} else{ //if we haven't expired:
$_SESSION['last_activity'] = time(); //this was the moment of last activity.
}
Also, put this code at the top of the page where you land when you've successfully logged in:
$_SESSION['logged_in'] = true; //set you've logged in
$_SESSION['last_activity'] = time(); //your last activity was now, having logged in.
$_SESSION['expire_time'] = 3*60*60; //expire time in seconds: three hours (you must change this)
On that page you don't have to include the checking code I gave you first.
By the way, don't forget to add `<?php` tags correctly!
Problem
I have created a script `login.php` and there I have created a session variable named `logged_in` ``` $_SESSION['logged_in'] = true; ``` I am unable to figure out a way to redirect to redirect to my logout.php after session expires due to inactivity. Also should I put the code that expire this session variable. I have Googled the bug and what it suggest is to tweak `php.ini` file in most of the articles. However I came across an article saying that it is not the best practice. I found the following code on StackOverflow, yet I have no idea where to put it:- ``` <?php if ($_SESSION['timeout'] + 10 * 60 < time()) { // session timed out } else { // session ok } ?> ``` I would like to know the best way to redirect after session expire and suggestions for where to put the code. Edit: I forgot to mention that I want to know how to manually set a time for the session to expire. Thank you in advance