What is the best way to handle sessions for a PHP site on multiple hosts?

PHP stores its session information on the file system of the host of the server establishing that session. In a multiple-host PHP environment, where load is unintelligently distributed amongst each host, PHP session variables are not available to each request (unless by chance the request is assigned to the same host — assume we have no control over the load balancer).

This site, dubbed “The Hitchhikers Guide to PHP Load Balancing” suggests overriding PHPs session handler and storing session information in the shared database.

What, in your humble opinion, is the best way to maintain session information in a multiple PHP host environment?

UPDATE: Thanks for the great feedback. For anyone looking for example code, we found a useful tutorial on writing a Session Manager class for MySQL which I recommend checking out.


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Database, or Database+Memcache. Generally speaking sessions should not be written to very often. Start with a database solution that only writes to the db when the session data has changed. Memcache should be added later as a performance enhancement. A db solution will be very fast because you are only ever looking up primary keys. Make sure the db has row locking, not table locking (myISAM). MemCache only is a bad idea… If it overflows, crashes, or is restarted, the users will be logged out.

Method 2

Whatever you do, do not store it on the server itself (even if you’re only using one server, or in a 1+1 failover scenario). It’ll put you on a dead end.

I would say, use Database+Memcache for storage/retrieval, it’ll keep you out of Zend’s grasp (and believe me things do break down at some point with Zend). Since you will be able to easily partition by UserID or SessionID even going with MySQL will leave things quite scalable.

(Edit: additionally, going with DB+Memcache does not bind you to a comercial party, it does not bind you to PHP either — something you might be happy for down the road)

Method 3

Storing the session data in a shared db works, but can be slow. If it’s a really big site, memcache is probably a better option.

Method 4

Depending on your project’s budget, you may also consider Zend Platform for your production machines, which in addition to a bunch of other great features, includes configurable session clustering, which works sort of like a CDN does.

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x