How To Set Session Length in PHP
- 1 minute read
Dealing with sessions expiring early in PHP can be frustrating, especially if you’re building an app and want to keep the user logged in for let’s say, two weeks.
Simply paste the following code before your session_start()
:
ini_set('session.gc_maxlifetime', 3600);
This tells your server to retain session data for at least 3600 seconds, which is one hour.
If you’d like to keep session data for two weeks, you could use the following code:
ini_set('session.gc_maxlifetime', 604800);
A more readable approach
PHP thinks in terms of seconds.
Larger periods of time are less readable to us humans.
So, here’s a more readable way to modify your session length:
$hour = 3600;
ini_set('session.gc_maxlifetime', $hour * 24); // One day
// OR
$day = 86400;
ini_set('session.gc_maxlifetime', $day * 7); // One week
Conclusion
There’s lots of different solutions online, but this is the only one that actually worked for me, at least in PHP 7.
Have a great day!