faqts : Computers : Programming : Languages : PHP : Common Problems : Sessions and State

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

59 of 80 people (74%) answered Yes
Recently 6 of 10 people (60%) answered Yes

Entry

What are the advantages of storing session data in a database and not a file?
Should I use database session handling or file session handling?

Sep 28th, 2001 22:45
Sam Johnston, Nathan Wallace, Sascha Schumann, Richard Lynch


By default, PHP stores session information in temporary files named
after the session ID. This approach is fast and simple, but not
necessarily scalable (although the speed of modern filesystems should
not be underestimated).

If you need multiple web servers to know about session state (ie
failover or load balancing where requests from any given client can't be
guaranteed to be answered by the same web server each time) or need to
access the session information from other applications (mod_perl, java,
etc) then you will definitely want to store session information in a
database. In the latter case you will also want it in a cross platform
format (ie WDDX http://www.wddx.org) Similarly, if you have many active
sessions (long timeouts and/or many clients) then you will run into
issues with large numbers of files chewing up filesystem resources
(inodes/blocks). If you have only one web server and a reasonably light
load, files are probably good enough, although a database may still
offer some advantages.

PEAR Session (http://sourceforge.net/projects/pearsession) is a custom
session handler which allows you to use any of the databases supported
by PEAR (http://www.php.net/pear) for the storage of session data. This
includes MySQL, MS SQL Server, PostgreSQL, mSQL, Interbase, Oracle etc.
It requires minor, if any, change to existing code and leverages PHP4's
built in session handling features.

If you are concerned about performance you should spend time building
samples and fake data and pounding on a server to find bottlenecks. It
shouldn't be too hard to do a side-by-side comparison of file versus
database session-handling. Don't underestimate the speed of free
databases like MySQL and later versions of PostgreSQL, which often
outperform their overpriced commercial counterparts.