- PHP session time set unset and check existence
- Quick example
- About PHP session
- PHP session lifetime settings
- Example: Working with PHP session time – Set expiration and limit lifetime
- Landing page to set session
- Check PHP session time via JavaScript AJAX
- Set unset PHP session time
- Conclusion
- Comments to “PHP session time set unset and check existence”
- How does PHP detect that a session has timed out?
- 1 Answer 1
- PHP: how to detect if a session has expired automatically?
- 13 Answers 13
PHP session time set unset and check existence
PHP session is one of the methods for keeping data persistency on the server side.
PHP sessions have a deadline time limit for keeping data persistent. PHP configuration file includes directives to have this specification.
We can also create custom code to change the default PHP session deadline.
This article contains sections that describe the PHP sessions, their time-limit configurations. It provides examples for setting session limits and tracking existence.
The below example gives a quick solution to set PHP session time . It contains only two steps to set and track the session expiration status.
Quick example
1. Create a file set-session.php and set value and lifetime.
"blue", "time" => $currentTime, "life_time" => 5 ); ?>
2. Create a file check-session.php to compute if the session existence.
About PHP session
We have already seen PHP sessions and cookies in a previous article. PHP sessions are for managing application data, state persistent during the working flow.
There are a lot of uses of sessions in an application. The below list shows some of the states or data managed by the use of sessions.
- Managing shopping cart in session.
- Keeping user logged-in state in session.
- Store the User-selected language in session in a multi-lingual website.
We have seen how to create a login script using the PHP session. In that, the session lifetime tracking can be used to log out after few minutes of inactivity.
PHP session lifetime settings
This section describes the configuration directives used to set PHP session time. The below table shows two PHP.ini settings related to the session.
PHP directive | Description |
---|---|
session.gc_maxlifetime | It sets the max lifetime after which the session will be elapsed and collected as garbage. |
session.cookie_lifetime | It sets the time limit for the session cookie in seconds. Default is 0 which means to be persistent until the client quits. Note: PHP session_set_cookie_params() sets all the session cookie parameters in runtime. |
The below PHP info highlights the session configuration settings. Refer to more runtime session configuration directives in the linked official site.
Example: Working with PHP session time – Set expiration and limit lifetime
This PHP session time handling example is the enhanced version of the above quick example.
It creates three session variables to set color, shape and size. It sets the lifetime for each PHP session variable while setting values.
The PHP code checks if the session exists. Once the time is reached, it unset that particular session variable and destroys it.
Landing page to set session
The landing page of this example shows a control to set the PHP session time. Once started, the session expiration status is checked at a periodic interval. This page includes the AJAX script to raise the call to PHP to check the session.
If the PHP session time is over, then this page will display a notice to the user. After all the sessions are expired, then the page will clear the notification and ask to reset the session.
Set PHP session time Reset Session
Check PHP session time via JavaScript AJAX
This script sets an interval to call the AJAX script to check the PHP session time. After getting the response, this AJAX success block shows the expired PHP sessions.
It checks the PHP session time every 5 seconds via AJAX. This script uses JavaScript setInterval() to invoke the checkSession() method.
if($('.session').data('status') != "") < var interval; interval=setInterval(checkSession, 5000); $("#status").text("Checking session expiration status. "); >function checkSession() < $.ajax(< url:"check-session.php", method:"POST", success:function(response)< if(response!="")< if(response == -1)< $("#status").hide(); clearInterval(interval); window.location.href='index.php'; >else < $("#message").append(response); >> > >); >;
Set unset PHP session time
In this section, it shows two PHP files to set and unset the PHP session time.
The set-session.php is called on clicking the UI control on the landing page. It sets the color, shape and size in the PHP session.
Each session array is a multi-dimensional associative array. It has the details of PHP session set time, lifetime and value.
The session set-time and lifetime are used to calculate the session expiry.
$currentTime = time(); $_SESSION['color'] = array( "value" => "blue", "time" => $currentTime, "lifetime" => 3 ); $_SESSION['shape'] = array( "value" => "circle", "time" => $currentTime, "lifetime" => 5 ); $_SESSION['size'] = array( "value" => "big", "time" => $currentTime, "lifetime" => 10 ); header("Location: index.php?status=starts"); exit(); ?>
This code returns the response text once the session is expired.
It validates the session expiry by comparing the remaining time and the PHP session lifetime.
Once all three sessions are expired, then this code returns -1. On receiving -1, the AJAX callback stops tracking by clearing the interval.
if (! isset($_SESSION['color']) && (! isset($_SESSION['shape'])) && (! isset($_SESSION['size']))) < print - 1; >if (isset($_SESSION['color'])) < $sessionTimeColor = $_SESSION['color']['time']; $sessionLifeTimeColor = $_SESSION['color']['lifetime']; if ((time() - $sessionTimeColor) >$sessionLifeTimeColor) < unset($_SESSION['color']); print 'Color Session Expired'; > > if (isset($_SESSION['shape'])) < $sessionTimeShape = $_SESSION['shape']['time']; $sessionLifeTimeShape = $_SESSION['shape']['lifetime']; if ((time() - $sessionTimeShape) >$sessionLifeTimeShape) < unset($_SESSION['shape']); print 'Shape Session Expired'; > > if (isset($_SESSION['size'])) < $sessionTimeSize = $_SESSION['size']['time']; $sessionLifeTimeSize = $_SESSION['size']['lifetime']; if ((time() - $sessionTimeSize) >$sessionLifeTimeSize) < unset($_SESSION['size']); print 'Size Session Expired'; > > exit(); ?>
Conclusion
Thus we have learned how to set PHP session time via programming. This article described the PHP configurations to set max session lifetime.
I hope this example helped to create your own code to manage PHP sessions and time.
Download
Comments to “PHP session time set unset and check existence”
It’s great Information about sessions in Php. Php session provides a way to store web page visitor preferences on a web server in the form of variables that can be used across multiple pages. In Php session unset is just cleared out the session for usage.
How does PHP detect that a session has timed out?
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?
1 Answer 1
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.
PHP: how to detect if a session has expired automatically?
When a session expiration time is defined, is it possible to call an event listener when it expires? If it is not possible, is it possible to run a cron job to check if a session has expired? NOTE: I’m interested in a server solution. I’m talking about the case there is a session expiration time defined, and the session finishes automatically because that period expired.
Do you want to call a php function? If you go through with doing this on the server, the timeout will be when the user attempts to go to another PHP page. Maybe you want to include some jQuery to load a php script that redirects the user and whatever else you need to be done.
13 Answers 13
is it possible to call an event listener when it expires?
The short answer is NO
There are a few oddities people tend to ignore about sessions. With the default handler, the session does not expire when gc_maxlifetime ends — this is just the time at which the data becomes eligible for automatic deletion. There is no action by the owner of the session which triggers the subsequent removal of the session — its a side effect of someone else’s session.
When session_write_close() is called (either explicitly, or implicitly by the code ending), if the random number generator, tweaked by the relevant gc settings throws the right number then PHP will go looking for data past its TTL and remove it. If you want to trigger an action at this point, then you need to break the default handler and apply your own. That means you not only have to provide a mechanism for identifying and removing sessions but also a way of deciding whether your handler should kick in and how many sessions it should delete — you don’t want a runaway process killing your server.
In Ubuntu, session.gc_probability = 0 , and it is a cron job which carries out the function of removing stale data files.
A very important piece of information missing from your question is the reason for deleting the session.
If you want to prevent sensitive data from persisting on the filesystem, then a better solution is to encrypt the data using a key stored (only) in another client side cookie. That way you completely eliminate the storage of unprotected data on your server. (note that suhosin’s encrypted sessions use a key derived from data about the client and a static key stored on the same host — this is significantly less secure than a randomly generated key). Here’s one I prepared earlier.
If you merely want to prevent access after the gc_maxlifetime has expired, you should consider a custom session handler which treats a stale session as missing. i.e. it doesn’t really logout at expiry, but any subsequent requests can no longer be associated with the session. The security layer in the Stackable session handler examples implements such a control.
OTOH if you want to use data from within the session in your event listener, then that’s a different story — you certainly won’t be able to use either Suhosin’s or my encryption for the data. But a further complication is that the (default) format for the data is different from that used elsewhere. 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() . session_decode() however will happily convert anything you throw at it.
In recent versions of PHP you can specify a different function pair to use for serialization/deserialization.
It is vitally important to consider the potential impact of __wakeup() methods when considering a session garbage collector which is going to read the data in the session files. Related to this is a requirement that the process which handles such garbage collection runs under the same uid as the original PHP process which created the session data (otherwise you have a privilege escalation backdoor). But if the session storage substrate is file-based then that would need to be the case anyway.
There are implementations of session data deserializer written in languages other than PHP which would provide protection against __wakeup() attacks (try Google) although that might be overkill to solve the problem and they are probably not being actively maintained. If this is a concern then a more appropriate solution might be to use the WDDX (xml) serializer and use a conventional XML parser to read the data back in your GC engine.
If you are using the native handler for normal reading and writing of the data but want to implement your own garbage collector then you’re going to need code to map the session_id to a file path. If you follow the link I gave to the PHP classes above, you’ll see pure PHP implementation of several session handlers, including ones which are compatible with the native handler.
But I would strongly encourage you to exhaust every other avenue for solving whatever the underlying problem is before choosing to read back session data at the time of deletion.