Increase php session time

前端 未结 5 423
没有蜡笔的小新
没有蜡笔的小新 2021-02-05 12:41

I am trying to increase my php session time to 6 hours.

Here is the code to increase the session time:

ini_set(\'session.gc_maxlifetime\', 60 * 60 * 6);          


        
5条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-05 13:25

    The scenario

    You’re running Debian Linux or Ubuntu Linux. You want PHP sessions to last longer than the default 1440 seconds (24 minutes). So you do this:

    ini_set('session.gc_maxlifetime', 10800);    # 3 hours
    

    With this setting, sessions should remain active for at least three hours, as long as users don’t close their browser.1

    But no matter what you do, sessions keep getting deleted after 24–54 minutes. It seems PHP is ignoring the gc_maxlifetime setting.

    Why this happens

    Debian and Ubuntu Linux override PHP’s session behavior. If you look closely, you’ll see that session.gc_probability is set to 0, meaning PHP’s garbage collection will never run. Instead, there’s a Debian-specific cron job in /etc/cron.d/php5 that runs every 30 minutes!

    The cron job does garbage collection based on the global session.gc_maxlifetime in php.ini. The session.gc_maxlifetime in your app is ignored.

    The solution

    While you could disable the cron job and/or modify php.ini, I’d prefer to fix the problem without modifying system defaults. A better solution is to create your own sessions directory, somewhere outside the normal one, and then locally enable PHP’s session garbage collection.

    To do this, set session.gc_maxlifetime, session.gc_probability, session.gc_divisor, and session.save_path:

    # Session lifetime of 3 hours
    ini_set('session.gc_maxlifetime', 10800);
    
    # Enable session garbage collection with a 1% chance of
    # running on each session_start()
    ini_set('session.gc_probability', 1);
    ini_set('session.gc_divisor', 100);
    
    # Our own session save path; it must be outside the
    # default system save path so Debian's cron job doesn't
    # try to clean it up. The web server daemon must have
    # read/write permissions to this directory.
    session_save_path(APP_PARENT_DIR . '/sessions');
    
    # Start the session
    session_start();
    

提交回复
热议问题