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

Simon Young picture Simon Young · Sep 16, 2008 · Viewed 7.8k times · Source

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.

Answer

John Campbell picture John Campbell · Sep 16, 2008

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.