Saving PHP Session Data to a Database
By Tony Marston2005-07-11
Introduction
As you should be aware the HTTP protocol, as used for serving web pages, is completely stateless. This means that after the server has received a request, processed it and sent a response, the process which dealt with that request dies. Anything that the process had in its memory therefore dies with it, so when a subsequent request is received from the same client it is unable to refer to its memory about anything that happened previously.
Fortunately PHP provides a standard method of maintaining memory (state) between requests in the form of Session Handling functions. This allows the programmer to maintain a set of variables in the $_SESSION array which is automatically saved to persistent storage at the end of each script, and then automatically loaded back into memory when a subsequent request is received from a client which supplies the same session_id.
By default the medium used as persistent storage by the session handler will be a series of disk files, one per session, where the file name is the session_id. A file is created khan a new session starts, and is deleted when the session terminates (or has expired). This is perfectly adequate for most circumstances, but it has the following drawbacks:
- If you are using a shared server then other users of that server may be able to access your session files, thus compromising the security of your site.
- Each server will have its own directory where these session files are maintained, so if you are employing load balancing across multiple servers there is no guarantee that a request for an existing session will be given to the server which is maintaining the state for that session.
- It would be difficult for a site administrator to perform such queries as "how many sessions are currently active?" or "which users are currently logged in?"
The authors of PHP have provided the ability to store session data using a method other than disk files by means of the session_set_save_handler function. This document will show how I have used this function to store all my session data in my application database.
Tutorial Pages:
» Introduction
» Define database table
» Define database class
» Define session handler
» Conclusion
