How to make PHP session expire after X minutes

MarPlo
Posts: 88

How to make PHP session expire after X minutes

In "login.php" it is set a session ID for the logged user. Something simple:

Code: Select all

<?php session_start(); // check login data received from a form .. if($okdata === true) { $_SESSION['user_id'] = $uzer; header("Location: index.php"); } else { echo 'Incorrect name or password'; }
In "index.php" I check if the $_SESSION['user_id'] exists, and display content according to user logged or not.

Code: Select all

<?php session_start(); if(!isset($_SESSION['user_id'])) {   echo 'User not logged'; } else {   echo 'User logged'; }
Now, how can I make the $_SESSION['user_id'] expire after 30 minutes?

Admin
Store a timestamp in the session.
In "login.php", register a session with the expired timestamp (when you want to expire that session) in the same time when the $_SESSION['user_id'] is created. Then, in "index.php" check if the current time exceds the expired timestamp.
Something like this:
"login.php - where the sessions are created

Code: Select all

<?php session_start(); // check login data received from a form .. if($okdata === true) {   $_SESSION['expire'] = time() + 30 * 60;  // expire after 30 minutes   $_SESSION['user_id'] = $uzer;   header("Location: index.php"); } else {   echo 'Incorrect name or password'; }
index.php

Code: Select all

<?php session_start(); // check if the sessions exist. If current time exceds $_SESSION['expire'], unset sessions if(isset($_SESSION['expire']) && isset($_SESSION['user_id'])) {   if(time() > $_SESSION['expire']) {     unset($_SESSION['expire']);     unset($_SESSION['user_id']);   } } if(!isset($_SESSION['user_id'])) {   echo 'User not logged'; } else {   echo 'User logged'; }

Similar Topics