Can anyone know when the user session data is cleared on the session lifetime expired?
Scenario: Laravel session lifetime is set to 2minute. when a user is logged in & idle for 2 or more than 2 min & refreshes the page it is redirected to the login page.
I want to know at which place the session is cleared.
If you use the default session driver 'file', the function 'gc' (/vendor/laravel/framework/src/Illuminate/Session/FileSessionHandler.php) checks if sessions are expired.
public function gc($lifetime): int
{
$files = Finder::create()
->in($this->path)
->files()
->ignoreDotFiles(true)
->date('<= now - '.$lifetime.' seconds');
$deletedSessions = 0;
foreach ($files as $file) {
$this->files->delete($file->getRealPath());
$deletedSessions++;
}
return $deletedSessions;
}
Hello @mvd,
This code is called based on the lottery value mentioned in the session.php file. I've checked it's not called every time when session is cleared.
the session just expires, ie, it is no longer valid by virtue of being past the end time. Each time the client sends in a request, the end time is extended to the full session lifetime.
in the case of file and database session storage, laravel runs a process to clear out old sessions on a lottery as part of the request cycle
If you are looking to run something the moment the session expires, then you are out of luck
Hello @Snapey,
Will the client send any request to the server to clear the session? means I like to know more about how laravel OR the sever clears the session & in laravel where it checks that the session is removed & redirected to the login page
@Kailas Bedarkar no, sessions aren't cleared by apps. Apps like Laravel define a expiration date and PHP process clears the expired sessions.
If you REALLY want to control when session are cleared, then you should clear it by yourself. Set a session time to 60 min and clear it yourself after 30m: you may add a AJAX request to run every 1 min to check the session status. Returns "true" if session is still alive. If time > 30 min, you clear the session and return "false".
@Snapey
I've updated the session.lifetime to 525600 min (1yr) & in middleware I've checked with the session value of "last_activity" value is greater than 120minute then update user status in DB & logout the user.