Home > Backend Development > PHP Tutorial > How to Make a PHP Session Expire After 30 Minutes of Inactivity?

How to Make a PHP Session Expire After 30 Minutes of Inactivity?

DDD
Release: 2024-12-20 03:29:13
Original
228 people have browsed it

How to Make a PHP Session Expire After 30 Minutes of Inactivity?

Expire PHP Session After 30 Minutes

Question:
How can I create a PHP session that will expire after 30 minutes?

Answer:

Method: Implement Custom Session Timeout

PHP's built-in session timeout methods, such as session.gc_maxlifetime and session.cookie_lifetime, are unreliable due to various factors. Instead, implement your own timeout using:

if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 1800)) {
  session_unset();
  session_destroy();
}
$_SESSION['LAST_ACTIVITY'] = time();
Copy after login

This code updates the session timestamp on every request, keeping the session file active and preventing premature deletion by the garbage collector.

Additional Security:

To protect against session hijacking, regenerate the session ID periodically:

if (!isset($_SESSION['CREATED'])) {
  $_SESSION['CREATED'] = time();
} else if (time() - $_SESSION['CREATED'] > 1800) {
  session_regenerate_id(true);
  $_SESSION['CREATED'] = time();
}
Copy after login

Notes:

  • Set session.gc_maxlifetime to be at least equal to the custom timeout (1800 in this example).
  • To expire the session after 30 minutes of activity, use setcookie with an expire time of time() 60*30.

The above is the detailed content of How to Make a PHP Session Expire After 30 Minutes of Inactivity?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template