views:

1615

answers:

4

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.

+1  A: 

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.

Aeon
+6  A: 

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.

althought i agree that DB+memcached is the best solution, i woudln't be so afraid of it crashing any more than the DB. and when it overflows, it should start with the oldest records, so the forced-logout would be to the laziest users. not so bad, as long as it seldom occurs
Javier
+1  A: 

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.

Peter Bailey
+1  A: 

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)

Jilles