Logout Idle/Inactive Users Using PHP

Today’s tutorial comes in the form of a PHP snippet that will automatically sign out idle or inactive users on your site.


Three functions are involved to complete the inactive session task:

  • A function to check if the user is actually logged in using the isLogged function.
  • A function to check the time the page loaded, and when the last page was loaded.
  • A function to log the user out after period of inactivity.

It is better to have these three functions together in the same file, and have this file included on every page that requires a login to be viewed.

Function sessionX() must come after session_start()

Append the code below into your functions.php file.

<?php 
# Start a session 
session_start(); 
# Check if a user is logged in 
function isLogged(){ 
 if($_SESSION['logged']){ # When logged in this variable is set to TRUE 
 return TRUE; 
 }else{ 
 return FALSE; 
 } 
} 
# Log a user Out 
function logOut(){ 
 $_SESSION = array(); 
 if (isset($_COOKIE[session_name()])) { 
 setcookie(session_name(), '', time()-42000, '/'); 
 } 
 session_destroy(); 
} 
# Session Logout after in activity 
function sessionX(){ 
 $logLength = 1800; # time in seconds :: 1800 = 30 minutes 
 $ctime = strtotime("now"); # Create a time from a string 
 # If no session time is created, create one 
 if(!isset($_SESSION['sessionX'])){  
 # create session time 
 $_SESSION['sessionX'] = $ctime;  
 }else{ 
 # Check if they have exceded the time limit of inactivity 
 if(((strtotime("now") - $_SESSION['sessionX']) > $logLength) && isLogged()){ 
 # If exceded the time, log the user out 
 logOut(); 
 # Redirect to login page to log back in 
 header("Location: /login.php"); 
 exit; 
 }else{ 
 # If they have not exceded the time limit of inactivity, keep them logged in 
 $_SESSION['sessionX'] = $ctime; 
 } 
 } 
} 
# Run Session logout check 
sessionX(); 
?>     

Incoming search terms for the article:

Related Posts

eBag Toolkit

Creating a Psychedelic Art Effect in Your Portraits

Inspirational Photo Retouches By Cristian Girotto

Create Your Own Sticker Design Via Photoshop