HomeMySQL Page 3 - Custom Session Management Using PHP and MySQL
Advanced PHP Session Techniques - MySQL
In this PHP programming tutorial, we will look at how to create and manage your own custom sessions using LAMP with MySQL and PHP as the session storage engine.
Note that there are a number of ways to improve this process. First, putting all these functions into a session handling class would alleviate the risk of accidentally overwriting the $sessionDB variable or misuse of the session functions themselves.
Second, this technique doesn't make use of any kind of caching. Clearly, a session which is being actively used will need to be fetched from the database every single time there's a page load. Adding a layer of memcache (or using memcache exclusively) would speed up this process significantly.
Third, and most important for very complex organizations, is the fact that this technique still uses the PHP default session serialization format, which is not compatible with other programming languages. Now that your sessions are in a database, you should be able to crawl the database and examine the sessions using some kind of daemon in C, Python, or whatever language your organization uses for such tasks. However, due to the restrictive nature of the serialization format, you can't do that. Look into session_encode and session_decode for ways of potentially handling that, but note that session_encode does not accept an argument, it operates directly on $_SESSION and your custom session functions will still return data that will overwrite the current contents of $_SESSION.
Conclusion
Using the technique above (indeed, simply copying and pasting the code) will allow you to split your website across multiple servers and still allow a user to maintain their session regardless of which server they connect to. Putting your sessions in a database also allows you greater control of when garbage collection happens and is more reliable than straight filesystem access, especially for large numbers of sessions.