I'm wondering how PHP detects that a specific session has timed out.
In detail: I'm using the default (file based) session handler, with a default session lifetime and so on. Everything in php.ini is on default.
If now a session is started, PHP does a check (depending non session.gc_divisor and session.gc_probability) if there are any timed out sessions. But from where does get PHP the last session access time from the sessions to check against?
The session file itself contains only the workload, e.g. x|i:1;
for a $_SESSION['x'] = 1;
, so there is no information about the last session access time.
I think that there are no in-memory information related to session start times as the sessions are still working after a full server restart.
So, where does PHP get the information from? Is it comparing the mtime/ctime of the session file?
You need to use session_encode() and session_decode(). The former will only read data from the $_SESSION array so eavesdropping on sessions requires some careful subversion of session_id() and session_start() .
The timeout limit of the session can be set by setting the value of two directives in the php. ini file or using the ini_set() function in the PHP script. The directives are given below. It is used to set the time limit in seconds to store the session information in the server for a long time.
The session functions keep track of users by issuing them cookies with a randomly generated session IDs. If PHP detects that a user doesn't accept the session ID cookie, it automatically adds the session ID to URLs and forms.
If IsSessionExpired() function returns true, you can do appropriate action, like show a message in label control which informs user that session is expired, redirect user to some SessionExpired. aspx page etc.
PHP's default session handler stores the $_SESSION data in a file using serialize()
, in the directory specified by session.save_path
. Generally the filename looks something like $filename = 'sess_' . session_id()
.
Since it's just a file, PHP can use the file's mtime (time of last modification) to determine which session files are stale. Basically it'll grab all the session files whose mtime exceeds the session.gc_maxlifetime
value and unlink()
them. As you've said, the probability of the cleanup occuring is governed by the session.gc_*
ini variables.
Now, if you create your own session handlers with session_set_save_handler()
, this is all out the window, and you've now got control over how sessions are stored and cleaned up, but this does explain the default behavior.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With