Choosing the appropriate option

In its default implementation (as above), you should not use sessions in very large projects which are likely to be deployed on multiple load-balancing servers. The reason behind this may not be apparent at first, but if you recall, session data is actually stored in a file on a server's computer. If a user visits your site, and your load-balancer redirects them to one server for a request, that server has their session data. Next time they read a page, your load-balancer may well shift them to another server, leaving their original session data on the original server. The second server might also save some session data of its own.

The end result? They lose their information part-way through their visit, and what data you do have is fragmented across your servers. There are ways around this problem, never fear:

  • Use a networked file system (NFS on Unix or the equivalent). Pretty much all operating systems allow you to connect to other computers and read/write their data. If you have a shared session data source, you would be able to bypass the above problem

  • Write your own session implementation that stores data in a medium you can handle and share between all computers. This is tricky, and error-prone.

  • Use a database to store your sessions.

 

Want to learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: Using cookies >>

Previous chapter: Sessions

Jump to:

 

Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.