0

A case for PHP session handlers

Posted September 28th, 2015 in Razno and tagged , by Metod

tl;dr: Don’t blindly write @session_start(); and hope for the best. Use a session handler!

A case for PHP session handlers

Not long ago, we were in transition from using Memcache to using Redis. Up until that point we were saving sessions to Memcache, but due to reasons beyond the scope of this blog post, we decided to migrate to Redis. As for any smooth transition, we kept Memcache up and ran Redis beside it so there would be no downtime in between deployments. After the deploy all went well. All apps were up and running. We decided to keep Memcache up for a few more days, just in case. And we forgot about that.

After some time, a system admin notices we still have Memcache up. Obviously the transition to Redis was made and we don’t need Memcache anymore, so he shuts it down. Suddenly some parts of the system start failing. Red alert, this cannot be good, why is it trying to connect to Memcache, when we removed all code related to it? So what was going on?

Lesson learned

We deploy our own configuration of session storage and caching etc. We do not rely on the server configuration, as it is not flexible enough. There was nothing wrong with our configuration. But, one of the developers wrote the following snippet of code in one of the component dealing with Facebook SDK (which requires an active session to connect a new user):

  1. <?php
  2.  
  3.  

Yes, he even suppressed errors, so we received no error messages related to that particular line of code.

There was no session handler in place. Coincidentally, the servers had session.save_handler and session.save_path set to Memcache servers and everything worked just fine. Up until the point when the system admin decided to shut down those Memcache servers.

Lesson learned. We managed to quickly resolve the issue by putting our existing session handling system in place. So, please, please, always make sure you know where and how your sessions will be stored. Especially if you are writing an app that is running in high-availability infrastructure.

How to write a session handler

Writing a session handler could not be easier. If you are running PHP >= 5.4 – and you should! – this is as easy as implementing the \SessionHandlerInterface. There is a nice example in the PHP documentation. For Memcache and Redis there are probably a lot of already written session handlers out there as well.

Finally

This was a short post on how something so simple can go pretty much very wrong. So I hope this will at least make someone not repeat the same mistake when dealing with sessions. Happy coding!