How to change the lifespan of a session?

There are several ways to modify the session’s lifespan.

  1. Update the session expiration time in the configuration file. You can modify the session.gc_maxlifetime parameter in the php.ini configuration file to set the maximum lifetime of the session in seconds. Locate the php.ini file, search for session.gc_maxlifetime, change its value to the desired time, save the file, and then restart the server.
  2. Modify the expiration time of sessions in PHP code. You can use the session_set_cookie_params function to set the expiration time of sessions. This function takes three parameters: expiration time (in seconds), path, and domain. For example, set the session lifetime to 1 hour.
$expire_time = 60 * 60; // 1小时
session_set_cookie_params($expire_time, '/');
session_start();

This will set the session expiration time to one hour and the path to the root directory.

  1. Manually destroy the session. You can destroy the session using the session_destroy function, which will immediately terminate the current user’s session. For example:
session_start();
session_destroy();

This will destroy the current user’s session, causing it to expire immediately.

It is important to note that regardless of the method being used, settings must be configured before the session_start function. Additionally, if a session expiration time is set, it is important to ensure that all pages have called the session_start function, otherwise the expiration time will not take effect.

bannerAds