ProblemYou want to use session storage for PHP scripts. SolutionPHP includes session management. By default, it uses temporary files for backing store, but you can configure it to use MySQL instead. DiscussionThis section shows how to use the PHP native session manager and how to extend it by implementing a storage module that saves session data in MySQL. If your PHP configuration has the TRack_vars configuration variable enabled, session variables are available as elements of the $HTTP_SESSION_VARS global array or the $_SESSION superglobal array. track_vars is always enabled as of PHP 4.0.3, so I'll assume that this is true for your PHP installation. If the register_globals configuration variable is enabled as well, session variables also exist in your script as global variables of the same names. However, this is less secure, so this variable is assumed not to be enabled here. (Section 19.5 discusses PHP's global and superglobal arrays and the security implications of register_globals.) The PHP session management interfacePHP's session management capabilities are based on a small set of functions, all of which are documented in the PHP manual. The following list describes those likely to be most useful for day-to-day session programming:
Specifying a user-defined storage moduleThe PHP session management interface just described makes no reference to any kind of backing store. That is, the description specifies nothing about how session information actually gets saved. By default, PHP uses temporary files to store session data, but the session interface is extensible so that other storage modules can be defined. To override the default storage method and store session data in MySQL, you must do several things:
Creating the session table. Any MySQL-based storage module needs a database table in which to store session information. Create a table named php_session that includes the following columns: CREATE TABLE php_session ( id CHAR(32) NOT NULL, data MEDIUMBLOB, t TIMESTAMP NOT NULL, PRIMARY KEY (id), INDEX (t) ); You'll recognize the structure of this table as quite similar to the perl_session table used in Section 20.1 for the Apache::Session Perl module. The id column holds session identifiers, which are unique 32-character strings (they look suspiciously like Apache::Session identifiers, which is not surprising, given that PHP uses MD5 values, just like the Perl module). The data column holds session information. PHP serializes session data into a string before storing it, so php_session needs only a large generic string column to hold the resulting serialized value. The t column is a TIMESTAMP that MySQL updates automatically whenever a session record is updated. This column is not required, but it's useful for implementing a garbage collection policy based on each session's last update time. A small set of statements suffices to manage the contents of the php_session table as we have defined it:
These statements form the basis of the routines that make up our MySQL-backed storage module. The primary function of the module is to open and close MySQL connections and to issue the proper statements at the appropriate times. Writing the storage management routines. User-defined session storage modules have a specific interface, implemented as a set of handler routines that you register with PHP's session manager by calling session_set_save_handler( ). The format of the function is as follows, where each argument is a handler routine name specified as a string: session_set_save_handler ( "mysql_sess_open", # function to open a session "mysql_sess_close", # function to close a session "mysql_sess_read", # function to read session data "mysql_sess_write", # function to write session data "mysql_sess_destroy", # function to destroy a session "mysql_sess_gc" # function to garbage-collect old sessions ); The order of the handler routines must be as shown, but you can name them as you like. They need not necessarily be named mysql_sess_open( ), mysql_sess_close( ), and so forth. The routines should be written according to the following specifications:
To register the handler routines, call session_set_save_handler( ), which should be done in conjunction with informing PHP that you'll be using a user-defined storage module. The default storage management method is defined by the session.save_handler configuration variable. You can change the method globally by modifying the php.ini initialization file, or within individual scripts:
To make it easy to access an alternative session storage module, it's useful to create a library file, Cookbook_Session.php. The only thing a script need do to use the library file is to include it prior to starting the session. The outline of the file looks like this: <?php # Cookbook_Session.php - MySQL-based session storage module require_once "Cookbook.php"; # Define the handler routines function mysql_sess_open ($save_path, $sess_name) ... function mysql_sess_close () ... function mysql_sess_read ($sess_id) ... function mysql_sess_write ($sess_id, $sess_data) ... function mysql_sess_destroy ($sess_id) ... function mysql_sess_gc ($gc_maxlife) ... # Initialize the connection identifier, select user-defined # session handling and register the handler routines $mysql_sess_conn = FALSE; ini_set ("session.save_handler", "user"); session_set_save_handler ( "mysql_sess_open", "mysql_sess_close", "mysql_sess_read", "mysql_sess_write", "mysql_sess_destroy", "mysql_sess_gc" ); ?> The library file includes Cookbook.php so that it can access the connection routine for opening a connection to the cookbook database. Then it defines the handler routines (we'll get to the details of these functions shortly). Finally, it initializes the connection identifier, tells PHP to get ready to use a user-defined session storage manager, and registers the handler functions. Thus, a PHP script that wants to store sessions in MySQL performs all the necessary setup simply by including the Cookbook_Session.php file: require_once "Cookbook_Session.php"; NOTE
The interface provided by the Cookbook_Session.php library file exposes a global database connection identifier variable ($mysql_sess_conn) as well as a set of handler routines named mysql_sess_open( ), mysql_sess_close( ), and so forth. Scripts that use the library should avoid using these global names for other purposes. Now let's see how to implement each handler routine:
Using the storage module. Install the Cookbook_Session.php file in a public library directory accessible to your scripts. (On my system, I put PHP library files in /usr/local/lib/mcb and modify php.ini so that the include_path variable names that directory. See Section 2.3.) To try the storage module, install the following example script, sess_track.php, in your web tree and invoke it a few times to see how the information display changes: <?php # sess_track.php - session request counting/timestamping demonstration require_once "Cookbook_Session.php"; # needed for make_unordered_list(), get_session_val(), set_session_val() require_once "Cookbook_Webutils.php"; $title = "PHP Session Tracker"; # Open session and extract session values session_start (); $count = get_session_val ("count"); $timestamp = get_session_val ("timestamp"); # If the session is new, initialize the variables if (!isset ($count)) $count = 0; if (!isset ($timestamp)) $timestamp = array (); # Increment counter, add current timestamp to timestamp array ++$count; $timestamp[] = date ("Y-m-d H:i:s T"); if ($count < 10) # save modified values into session variable array { set_session_val ("count", $count); set_session_val ("timestamp", $timestamp); } else # destroy session variables after 10 invocations { session_unregister ("count"); session_unregister ("timestamp"); } session_write_close (); # save session changes # Produce the output page ?> <html> <head> <title><?php print ($title); ?></title> </head> <body bgcolor="white"> <?php print ("<p>This session has been active for $count requests.</p>\n"); print ("<p>The requests occurred at these times:</p>\n"); print make_unordered_list ($timestamp); ?> </body> </html> The script includes the Cookbook_Session.php library file to enable the MySQL-based storage module, and then uses the PHP session manager interface in typical fashion. First, it opens the session and attempts to extract the session variables. For the first request, the session variables will not be set and must be initialized. This is determined by the isset( ) tests. The scalar variable $count starts out at zero, and the nonscalar variable $timestamp starts out as an empty array. For successive requests, the session variables will have the values assigned to them by the previous request. Next, the script increments the counter, adds the current timestamp to the end of the timestamp array, and produces an output page that displays the count and the access times. If the session limit of 10 invocations has been reached, the script unregisters the session variables, which causes $count and $timestamp not to be saved to the session record. The effect is that the session restarts on the next request. Finally, sess_track.php calls session_write_close( ) to write out the changes to session data. The output page is produced only after updating the session record because PHP might determine that a cookie containing the session ID needs to be sent to the client. That determination must be made before generating the page body because cookies are sent in the headers. As mentioned earlier, we assume that register_globals is not enabled. Thus, we cannot use the PHP session_register( ) function to register session variables and it is necessary to access session variables another way. The two possibilities are to use the $HTTP_SESSION_VARS global array or (as of PHP 4.1) the $_SESSION superglobal array. For example, after calling session_start( ), a session variable named count will be available as $HTTP_SESSION_VARS[ "count" ] or $_SESSION[ "count" ]. It's possible to adopt an approach that uses the PHP session variable arrays but still enables you to work with simple variable names to manipulate session variables:
However, it's messy to determine which global array to use for session variable storage because that may depend on your version of PHP. Instead of making this determination each time you want to access a session variable, it's easier to write a couple of utility functions that do the work. That is the purpose of the get_session_val( ) and set_session_val( ) functions used in the script. They access session variables for the counter value and timestamp array and store modified values back into the session: function get_session_val ($name) { global $HTTP_SESSION_VARS; $val = NULL; if (isset ($_SESSION[$name])) $val = $_SESSION[$name]; else if (isset ($HTTP_SESSION_VARS[$name])) $val = $HTTP_SESSION_VARS[$name]; return ($val); } function set_session_val ($name, $val) { global $HTTP_SESSION_VARS; if (isset ($_SESSION)) $_SESSION[$name] = $val; $HTTP_SESSION_VARS[$name] = $val; } These routines can be found in the Cookbook_Webutils.php library file, along with the routines that get other kinds of web script parameter values (see Section 19.5). They are in Cookbook_Webutils.php rather than in Cookbook_Session.php so that you can call them even if you elect not to use the MySQL-based session storage that Cookbook_Session.php implements. |