How Can I Set A PHP Session To Expire After 30 Minutes?

To expire a PHP session after 30 minutes, you can use the session.cache_expire and session.gc_maxlifetime directives in your PHP configuration or in your code.

  1. Using PHP configuration file (php.ini):
    a. Open your php.ini file.
    b. Locate the session.cache_expire directive and set it to 30. This sets the session cache expiration time to 30 minutes.
    c. Locate the session.gc_maxlifetime directive and set it to 1800. This sets the maximum lifetime of session data to 30 minutes.
    d. Save the php.ini file and restart your web server for the changes to take effect.

  2. Using PHP code (in your script):
    a. Add the following code at the beginning of your script, before any session_start() calls:

    ini_set('session.cache_expire', 30);
    ini_set('session.gc_maxlifetime', 1800);

    This will set the session cache expiration time to 30 minutes and the maximum lifetime of session data to 30 minutes.

  3. Combining both (php.ini and PHP code):
    If you have access to both the PHP configuration file and your script, it’s best to set these directives in the php.ini file and restart the web server. This way, the settings will be applied globally to all PHP scripts running on your server. The PHP code mentioned above can be used as a fallback in case you don’t have access to the configuration file.

Remember to call session_start() before accessing any session variables in your PHP script.

About the Author Rex

I'm a passionate tech blogger with an insatiable love for programming! From my early days tinkering with code, I've delved into web dev, mobile apps, and AI. Sharing insights and tutorials with the world is my joy, connecting me to a global community of like-minded tech enthusiasts. Python holds a special place in my heart, but I embrace all challenges. Constantly learning, I attend tech conferences, contribute to open-source projects, and engage in code review sessions. My ultimate goal is to inspire the next generation of developers and contribute positively to the ever-evolving tech landscape. Let's code together!