PHP Session Expiry

It's funny. Earlier this week I encountered this problem, and then just now, someone else writes about it. Though their problem is exactly opposite to the problem I encountered, the cause and the solution is the same. So what is the problem? In the php.ini, you can configure the session.gc_maxlifetime setting. This setting controls how long a session may live before the garbage collector kills it because it has expired. Then, in your own script, if you feel the php.ini setting is too short or too long, you can specify your own gc_maxlifetime by using ini_set(). So far, no problem. The problem we encountered was that our php.ini setting was set to something like 24 minutes, and we wanted 24 hours. So we used ini_set() to set the maxlifetime to that value, and still we got reports where a session would time out much earlier than expected. Not good. Last week, after a bit of digging, we found the cause of the problem. We have multiple applications running on this server that use sessions. Most use the default php.ini setting, and not this adapted setting. All sessions are saved in files in a directory (/tmp in our case). But when the garbage collector is triggered, it does not discriminate between sessions created using the default php.ini setting and the one we set manually. No problem when the garbage collector is triggered from our script. But a big problem when it's being triggered by the other applications. The garbage collector will go through the /tmp directory and see a lot of session files that have expired. It will delete them. Gone is your session that should've lived for 24 hours. This is, in my very humble opinion, a big shortcoming in PHP's session handling. There is an easy work-around though: those of your applications that use a custom gc_maxlifetime should also be saving the session files to a different session.save_path. Here also, ini_set() will support you in setting this value. This should of course point to an existing directory which is writable by your php/webserver user. Now, the next step of course, would be that php would change their session handling. I can not imagine this being too hard. Each session file would, aside from the already present (serialized) session data, contain a tag that is in some way seperated from the actual session data. This tag contains the timestamp of the session's expiration. When a session is being written, the session handler can easily calculate the moment of expiry for the session based on the current timestamp + active session.gc_maxlifetime. Now, when the garbage collector is triggered, it need only read the first line of each session file and purge the files that have a timestamp lower than the current time. I understand that this is probably slightly more resource-intensive than just reading the timestamp of file, but it would enhance php's error handling in such way that I personally feel this is not a problem. It could even be an optional php.ini setting (session.enhanced_session_lifetime = 1). Of course, I'm not in the PHP group, so I guess for now I'll just have to implement a custom session handler with this functionality. Quite a pain though, since I'll have to do this with all my sites then. Or just implement the above fix of course ;)
Add comment

Comments

gravatar murugavel: My Pbm is I am using the session in my program .I am geting page expired error how to solve this problm
June 2, 2006
gravatar Steven Van Poeck: I’m not so sure I’d like PHP writing timestamps on my sessions…
Because that means PHP will have to write and update that part each and every time it accesses your session data. Is that not a bit overdone ?

I prefer putting session that need special care in a separate directory. That also makes it nicely separated from the “regular” session data on your server’s disk. As you surely do for the logfiles for each virtual host you have installed :)

Steven
June 6, 2006
gravatar left: well, the funny thing is, PHP currently also needs to at least touch the session file every time the session is active, because else the garbage collector would also get rid of it. That is currently also the way of “refreshing” your data’s lifetime.

I agree that of course the best way to keep things seperated is to have seperate directories set up for special sessions, however, by default, you can set the maxlifetime without setting the save_path. And so I’d expect PHP to at least be able to handle one without the other.
June 7, 2006
gravatar Lab walk: I am using the following code. But the session is not expiring even after 10 Mins also Help Plzz.

ini_set('session.gc_probability', 100);
ini_set('session.cache_expire', 1);
ini_set('session.cache_limiter', 'none');
ini_set('session.cookie_lifetime', 60);
ini_set('session.gc_maxlifetime', 60);
July 9, 2008
gravatar creativeAngel: i am facing some what same problem, i used to store user login information on my site, when i tried to check how many users are online it shows all users online who may offline due to session expiration because this information is not save back in database. how can i handle it please guide me.. :(
July 16, 2008
gravatar Time Warner Cable Promotions: Really I appreciate your blog. Thanks for sharing!
February 24, 2012
gravatar Time Warner Internet Deals: This article will help everyone to know so much important information.
February 24, 2012
gravatar camping trailers: Most software has software documentation so that the end user can understand the program, what it does, and how to use it. Without clear documentation, software can be hard to use especially if it is very specialized and relatively complex like Photoshop. Thanks.
April 19, 2012

Php5_zce_logo

Upcoming events

I will be speaking 05-06-2012: Forum PHP
I will be attending 06-06-2012: Symfony Live Paris 2012
I will be attending 07-06-2012: Symfony Live Paris 2012
I will be attending 08-06-2012: Symfony Live Paris 2012
I will be attending 09-06-2012: Symfony Live Paris 2012
I will be attending 23-06-2012: PHP TestFest NL

Tags

1337 2008 2010 2011 4developers access modifiers accessibility AdaLovelaceDay09 advent agavi agile alfred amsterdam apache api apple article articles atk atkMetaNode audioscrobbler autoloading automation azure backwards compatibility barcelona barcodes bash bbc bbq beatstad belgium best practices bittorrent blogging blogs boards of canada book books bughuntday bundle caching cake cal evans calendar career cat cerf certificate cfp cilex clear cms cologne common sense communities community components composer conference conferences contest continuous integration contribute contribution crisis css curl custom d-day datetime DbFinderPlugin decorator decorators deployment deps devdays development directoryindex directoryiterator docblox doctrine documentation download dpc dpc09 dpc10 dpc11 DPC2008 dreamhost drupal dv7 eclipse ed editors efficiency enterprise errors event events expertise ezcomponents facebook filter-branch filteriterator finland flickr fork framework frameworks freelance freeze frontend fun game games geoip germany getting real git github globiterator gnome-do google google calendar googletalk graceful degradation hack hackers hidden gem hiphop howto hp HR html http i386 ibuildings icann ide ideasofmarch idm imovie inclusivity indy ingewikkeld integration international php conference internet interview ipad IPC ipc ipc08 ipc10 ipc11se iterators iterm2 javascript jenkins jenkins-php job job openings jobeet john peel joomla joomladays kiva kubuntu launcher launchy left on the web libcurl libraries library lighttpd lime linktuesday linux live london loudblog m2ts mac magazines malware mambo marjolein mediterra meeting meme meta methodology micro-financing microframework microsoft migration movie music mysql namespace namespaces netbeans netherlands newsfire nllgg northeastphp nos odmarco open source opinion ORM osx paradiso paris partnership pavilion pear pecl performance personal pfc10 pfc11 pfcongres pfcongrez pfz photo php PHP php5.3 phpabstract phpazure phpBB phpbb phpbelgium phpbenelux phpbnl10 phpday phpdoc phpdocumentor phpgg phpitalia phpnw phpnw08 phpnw11 phpstorm phptek phptek09 phpuk2009 phpUnderControl phpunit php|architect php|tek podcast politics portability postcrossing presentation presentations private projects protected prototype PSR-0 public python qa qr codes re2c recruiting refactoring review rewrite ruby on rails san francisco schedule scifi script security sensio seven things sfdaycgn sflive2011 shell scripting silex simplexml slides smfony software sogeti solar sound speakers spl ssh standard standards star trek static steer strings stylesheets subversion symfony symfony live Symfony2 symfonycamp symfonyday symfonylive symfonyUnderControlPlugin talk talks tech techademy technology techportal tek09 telecommuting terratec terrorism testfest testing textmate textpattern the right tool timeout tips tld todo tomas tools training twig uncon unet usability usergroup validation vhost video vim vinyl virus warp webinar weblogging webservices wiki windows winphp women wordpress work workshop world world of warcraft wpi writing wunderlist xml xpath xsd yara year youtube zc11 ZCE zemanta zend zend framework zend server zend studio zendcon Zend_Form zite
© 2004 - 2012 Stefan Koopmanschap + Powered by Symfony, photos powered by Flickr, links powered by Delicious, Shanghai smilies by Iconbuffet. Feeds: rss / atom. Left on the Web v4.4.0.1