PHP Session variable timeout - php

My application uses some session variables that are timing out even though I thought they would not because I've got the following setting in php.ini:
session.cookie_lifetime = 0
The other session settings in php.ini are pretty much set as their defaults. How do I make sure the session variables stay around until the browser window closes?

I think you set the session timeout with session.gc_maxlifetime which defaults to 1440 seconds - 24 minutes

Note that since PHP 4.2.3 the life time is calculated on the base of the modification date and not the access date (see session.gc_maxlifetime). So you have to update the session data on every request to “reset the timer”.

Related

Session cannot remain for a long time its automatically destroyed

I have an issue with session , my session is automatically destroyed after few minutes of inactivity ,i think its must be 24 minutes i.e. 1440 seconds.I want to session remain for a long time , i am using .user.ini file on the server and set session.gc_maxlifetime to 31557600 seconds and session.cookie_lifetime to 31557600 but nothing happened for me .Its still logout after 1440 seconds of inactivity .I have also attached session value of png image of phpinfo.
I hope your answer or any help will work for me.Thanks.
I'm not sure why your settings aren't working but I use the following on my scripts to overwrite the php.ini settings for session maxlifetime and session_save_path:
session_save_path('/pathto/writable/dir/on/your/account');
ini_set('session.gc_maxlifetime', 24*60*60); // 24 hours; change as necessary
session_start();
NOTE:
The session_save_path is important because the default path is /tmp and it may get deleted by the system administrator on a daily/week? basis.
In my experience, it's always been related to the php.ini file. In your case, the master and local values for session.gc_maxlifetime contradict. (gc stands for garbage collect) They don't have to agree with each other, since the local value is used for the running script. It just means there's two php.ini files on your system, located in different places, and the local php.ini file is overriding the master php.ini file settings. But, I'd be VERY suspicious of any files on your server which call session_start() which use the master php.ini file, or call ini_set(...) within the script itself. The way this works is that no matter what the value is set to, it only has meaning when it's time to do garbage collecting. And garbage collecting is done by session_start() but you can also trigger garbage collecting in other ways such as SessionHandler::gc or a cronjob as explained later in this post. When called, it checks the last modified time of the file on the server storing your session information. If the number of seconds that elapsed since then is greater than the current session.gc_maxlifetime value, it will destroy the session. Note this is the last modified time, not the last accessed time, so you'll want to change your session data frequently to prevent it from getting deleted if it's not changing. You should also be aware that there is a setting here, called session.lazy_write which, if enabled, and is enabled by default, WILL NOT update the last modified time of the session file in the event which the session data did not change. Thus you'll want to disable this if you want to minimize the chances of sessions being destroyed early for some unknown reason, or store a timestamp on the session so the data is always changing and you know when the session was last used, if old, you can manually call session_destroy(). To start another session, you can commit with session_write_close() then recall session_start(). Or, do all 3 at once with session_regenerate_id(true).
Nextly, if you initialize a session with session_start() with your intended settings, and continue to call session_start() with the intended settings with each request, awesome. But, once any file on your server calls session_start() with a different value for session.gc_maxlifetime, either from using the master php.ini value in your case, or the script calling ini_set(...) and ignoring the master value, it will check the file's last modified time against a different value and destroy your session despite your intended settings - is assuming it gets elected to be one of the 1 in 100 requests which have to garbage collect.
Another thing to be concerned with is session.cookie_lifetime. A value of 0 here turns the cookie into a browser session cookie. This means if the user closes their browser, then the session cookie will be deleted by the browser. Your master value is using 0. But your local value is using 31557600 (the average seconds in a year). So you should be fine here. But keep your eyes open if any scripts on your server override this value, use a value of 0, or use the master php.ini file.
You should also be aware of the default 1% garbage collecting CHANCE that a session will be destroyed as defined by session.gc_probability and session.gc_divisor which default to 1 and 100 respectively. Garbage collecting is done when start_session() is called, if, and only if, the request "randomly" gets picked to be the request to manage the Garbage Collecting. This means that even if the number of defined seconds for a session elapsed for it to expire, start_session() STILL won't garbage collect even for this expired session. Rather, most users will notice their sessions expire exactly to schedule due to the cookie the browser keeps track of having its timestamp expire. But the session isn't enforced until PHP garbage collects as per the garbage collection change when start_session() is called. If you want sessions to be wiped clean when they've expired, and start a new one, you should use session_regenerate_id(true). The true here means trash the $_SESSION data tied to the previous session and toss them a different session id as though their session expired.
You should also be aware that some systems, such as debian-based systems, have a cronjob which runs every 30 minutes to garbage collect based on the master php.ini configuration information.
See the comment here by Christopher Kramer: http://php.net/manual/en/session.configuration.php
I cannot verify if the above information about debian systems is true, but I've considered garbage collecting with a cronjob before to speed up users' requests so no one user gets stuck having to wait for their request to go through due to the maintenance which a cronjob could be handling.
In terms of solutions here:
One solution here is to adjust the master php.ini value, if you have access to it, then search your server for any PHP files which might be calling ini_set to see if there's any files conflicting with your settings to make sure they're not causing the unexpected behavior.
Another solution would be to limit such conflicts the script might be encountering by: (1.) renaming the session.name to something other than PHPSESSID. And/or (2.) changing the session.save_path path. Either of these by itself would suffice and avoid script conflicts.
A temporary fix might be to do something like change your session.gc_probability to 0 so the session garbage collecting NEVER happens. Or make it a much smaller chance by using something like session.gc_probability=1 and session.gc_divisor=100000. Then setup a cronjob to call SessionHandler::gc
See http://php.net/manual/en/session.configuration.php for more session config information.
Lastly I'd like to point you to this post which suggests good practices to prevent session hijacking, and for the most-part is the post I referenced when putting this post together: https://stackoverflow.com/a/1270960/466314
Note that it uses an approach to sessions which makes sure sessions expire on time, and not later (although browsers do a good job of this already with cookie garbage collecting). And it also makes changes to sessions, keeping track of the session last used time, so the session data is always changing to avoid the issue with session.lazy_write.
This concludes my suggestions. If you can narrow down the issue, try searching stackoverflow or asking a new question.
As stated here :
The best solution is to implement a session timeout of your own. Use a
simple time stamp that denotes the time of the last activity (i.e.
request) and update it with every request:
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 1800)) {
// last request was more than 30 minutes ago
session_unset(); // unset $_SESSION variable for the run-time
session_destroy(); // destroy session data in storage
}
$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp
Updating the session data with every request also changes the session
file's modification date so that the session is not removed by the
garbage collector prematurely.

How long php sessions are stored in server?

I'm wondering how long php sessions are stored in server memory.What if user logs in (sets session variables in server) and he keeps his browser open for a long time suppose 30 days and he reloads the page on the 31st day? Can browser access session variables(browser still has session cookie)?
Default php.ini sets the session expiration time to 30 minutes.
Check out these settings: session.gc_maxlifetime and session.cookie_lifetime
As long as the browser have the cookie stored, it doesn't matter if it is closed or is open.
If you want to store the session for lets say 30 days, you can add:
ini_set('session.gc_maxlifetime', 30*24*60*60);
ini_set('session.cookie_lifetime', 30*24*60*60);
Normally you would code as part of your session handling code a function for expiring sessions after some time has elapsed, so in that case it would't matter how long they left there browser open
I think this depends on what you have set in php.ini http://php.net/manual/en/function.session-set-cookie-params.php

PHP Sessions expiry time - keeping session alive for a specific number of minutes/hours/days

I have a site that creates a Session for shopping carts.
$_SESSION['cart']=array();
It seems as if the server automatically kills the session after X time of inactivity, I assume this is set in php.ini (but my host does not grant me access, they just let me tell them the changes, so I cannot play around! :().
Is there a better way to keep the sessions alive for example for 2 days or for a specific number of minutes/hours?
Call session_set_cookie_params() before you call session_start() in your scripts:
$session_lifetime = 3600 * 24 * 2; // 2 days
session_set_cookie_params ($session_lifetime);
session_start();
// ...
From the documentation:
session_set_cookie_params()
Set cookie parameters defined in the php.ini file. The effect of this function only lasts for the duration of the script. Thus, you need to call session_set_cookie_params() for every request and before session_start() is called.
Alternatively, you could update your php.ini file's session.cookie_lifetime directive to 2 days (in seconds).
set a cookie and change in you config that the session use cookies
session_start();
set_cookie("PHPSESSID", session_id(), time() + 3600 * 2);
this keep alive your session for 2 hours

Kohana 3.2 session expires too soon, shorter expirations work as expected

Kohana 3.2 sessions are expiring too soon. My current config is:
return array(
'native' => array(
'name' => 'kohanasession',
'lifetime' => 0,
),
);
Using lifetime => 0 means that the session will end when the browser is closed. However, after 1 hour, the session expires.
I also tried to use a lifetime different (for example 36000 => 10 hours), but again, it failed.
If I use a tiny session life (e.g. 10 seconds) then the expiration works perfectly. As far as I checked, seems that if I want a session to have a lifetime longer than 1 hour, it will not work.
Finally, the relevant config we use for php.ini
session.save_handler = memcache
session.save_path="tcp://127.0.0.1:11211?persistent=1&weight=1&timeout=1&retry_interval=15"
session.cache_limiter = nocache
session.gc_probability = 0
I am really lost here. This should be simple to fix but I just cannot work it out.
The lifetime => 0 parameter is likely only affecting the session cookie's lifetime.
What's probably happening is that, while the cookie is working fine, you're throwing away the users' session data on the server side. PHP has session garbage collection that's a little odd by default: it marks sessions as expired after 24 minutes of idle time, and has a 1% chance on each request to clean up all the expired sessions.
You can increase the PHP ini setting session.gc_maxlifetime, or you could set session.gc_probability to zero to disable automatic session garbage collection entirely.
Of course, there's also the possibility that your memcached server is configured to throw away the data after some time period.
Update: For the average session handler, setting session.gc_probability to zero would be the way to go to disable the automatic cleanup entirely. However, the memcache session handler actually already doesn't do garbage collection (its gc callback does nothing). So, changing either of session.gc_probability or session.gc_divisor is pointless with that save handler.
Instead, the memcache save handler automatically sets an expiration when saving the session data to the memcached server (a la the expire param to Memcache::set). The handler reads the expiration time to use from the session.gc_maxlifetime setting. So, that's the only GC setting that really matters when you're using the memcache session save handler.

The question between session.gc_maxlifetime and session.cookie_lifetime

My first question in stackoverflow. Thanks in advance!
I am so confused about the PHP session mechanism. I have understand the session.gc_maxlifetime by PHP - ini_set('session.gc_maxlifetime', 5) - Why it doesn't end the session?. But I still don't know the difference between session.gc_maxlifetime and session.cookie_lifetime.
Question:
What will happened if the time of session.cookie_lifetime is out? Will the session cookie be deleted from the client computer directly?
I need to figure this question, then continue to ask something further.
session.gc_maxlifetime is the time in seconds after which your session data could be considered as garbage data. In other words, you can say that it is the time an unused PHP session will be kept alive.
session.cookie_lifetime is the life time in seconds of session cookies whether the session is alive or not. So the cookies will stay alive until the given time is elapsed
See:
http://www.php.net/manual/en/session.configuration.php#ini.session.gc-maxlifetime
https://blogs.oracle.com/oswald/entry/php_session_gc_maxlifetime_vs
The cookie lifetime is transmitted to the client. If the cookie has reched its lifetime, the client usually deletes it. So it is client-side. Also the a session can be alive even after the cookie is gone, since you can create the same cookie again, epand its lifetime, or transmit the session-id via the uri.
Hope that helps!

Categories