I have a MySQL table named 'session', when user logs in, IP is automatically recorded to that table so another person can not log in with same user, now I'm facing a problem, I want to destroy session automatically even if that user closes his browser and delete record from that table after inactivity of 5 min.
Firstly, it's important to realise that an IP address is not the same thing as a unique login. A user can very easily switch their IP around (or mask it), and you'll also want situations where people are using the same computer for different accounts.
What I would recommend is to have a traditional login system, and simply create a column called expiry
that is automatically set to be 5 minutes after the user first logs in. This could also be updated upon the user performing various activities on the website if you want to extend this 5 minute grace period.
On each of the 'secure' user pages that require the user to be logged in, you can simply run a SELECT
request against this column for the user that is logged in. If the timestamp in the database is found to be less than the current time, redirect the user to a forced logout page. If it is greater than the current time, the user is allowed to see the content on the page.
Here's a rough example:
date_default_timezone_set('YOUR ZONE');
$stmt = $con->prepare("SELECT `expiry` FROM users");
$stmt->execute();
$row = $stmt->fetch();
if($row['expiry'] >= NOW() ) {
// Valid, show content
} else {
header('Location: /logout.php');
}