Advanced SessionsCustom Session HandlingWith the basics of sessions out of the way, let's examine exactly how sessions work by customizing how sessions are handled internally. By default, PHP provides three internal methods of storing session data specified by session.save_handler: the internal PHP session file format (specified by php), within an SQLite database (specified by sqlite) and the WDDX packet format (specified by wddx).
When it comes to session handling, perhaps the most useful capability of PHP does not lie in the internal session handlers. Rather, PHP provides the means to completely customize session handling by allowing you, the developer, to specify your own PHP functions that will be used to save and restore session data as necessary. When using user-defined session handlers, six individual functions must be defined for sessions to work properly, as described next:
The six functions each have specific parameters and return values, as shown next:
To use a user-defined session handler, each function must be created and then registered using the session_set_save_handler() function. The syntax of this function is as follows: session_set_save_handler($open, $close, $read, $write, $destroy, $gc) Each of the six parameters represents the string name of the associated user-defined function. This function returns a Boolean indicating whether the custom session handler was installed successfully.
Custom session handlers don't do much good without more knowledge (such as the capability to access and work with databases from PHP). Now is not the time to show a complete example of custom session handlers at work. However, I have provided such an example in Chapter 26, "Using SQLite with PHP." Customizing Session SupportAlthough sessions in PHP can be a very easy tool to use, there are many complexities and customizations that are provided to allow the maximum amount of flexibility. This section will cover those configuration directives and session-related functions not already discussed elsewhere in the chapter and explain their use in practical PHP scripts. Although I have already mentioned a few session-related configuration directives, be aware that Appendix A contains a full listing and description of each directive, including those not discussed in this chapter. Along with the configuration directives for sessions support, PHP also provides a number of functions that help control the behavior of sessions within your scripts directly, without the need to modify the php.ini file. In most cases, these functions are named exactly as their configuration directive counterparts. For instance, to dynamically adjust the session.cache_limiter directive from a PHP script, the function session_cache_limiter() will do the trick. Because repeating these things will do nothing but take up space, I'll leave them out and instead refer you to the PHP manual where information regarding syntax can be found. ![]() |