Skip to content

Instantly share code, notes, and snippets.

@psdtohtml5
Last active September 5, 2021 16:09
Show Gist options
  • Save psdtohtml5/6090113 to your computer and use it in GitHub Desktop.
Save psdtohtml5/6090113 to your computer and use it in GitHub Desktop.
PHP : Auto expire session / Auto logout after specific time
<?php
//on pageload
session_start();
$idletime=60;//after 60 seconds the user gets logged out
if (time()-$_SESSION['timestamp']>$idletime){
session_destroy();
session_unset();
}else{
$_SESSION['timestamp']=time();
}
//on session creation
$_SESSION['timestamp']=time();
@mwoare
Copy link

mwoare commented Mar 13, 2019

Thanks for the snippet! I modified it to work php7

** put this line in your login script - must have already done a session_start() **
$_SESSION['timestamp']=time();

** Load this on every page **
session_start();

$autologout=1800; //after 15 minutes of inactivity the user gets logged out
$lastactive = $_SESSION['timestamp'] ?? 0; // Use of 'Null Coalescing Operator' - pulls the timestamp or sets it to 0.

if (time()-$lastactive>$autologout){
	    $_SESSION = array();                   // Clear the session data
                setcookie(session_name(), false, time()-3600);     // Clear the cookie
               session_destroy();                         // Destroy the session data
}else { 
		$_SESSION['timestamp']=time();              //Or reset the timestamp
	}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment