PHP DevCenter

oreilly.comSafari Books Online.Conferences.

We've expanded our LAMP news coverage and improved our search! Search for all things LAMP across O'Reilly!

Search
Search Tips

advertisement

Listen Print Subscribe to PHP Subscribe to Newsletters

Session Tracking: Part 2
Pages: 1, 2, 3

Once these functions are defined, you then need to tie them into the PHP session-handling logic. This is accomplished by passing their names into PHP's predefined session_set_save_handler() function. For example, assuming that the custom function names are those shown above, you would define them as custom storage handlers as seen below:



session_set_save_handler("session_open", "session_close", 
                         "session_read", "session_write", 
            "session_destroy", "session_garbage_collect");

Keep in mind that you can choose function names to be whatever you wish. What's important is that:

  • The function passes in as input the correct number and type of parameters.
  • The function names are defined in the correct order within the session_set_save_handler() function, that is: open, close, read, write, destroy, and garbage collect.

MySQL session-storage functionality

Thus far, I've defined the requirements as specified by PHP's user-defined session functionality. This information can then be applied to the media in which you would like to handle session data. In this section, I'll show you how this is accomplished with the popular MySQL database server.

Before creating the functions, the database table should be created. Listing 1 displays the table as I've created it. Depending on the level of activity you expect regarding the sessions table, you may also wish to create a database specifically for the sessions table. However, I'll leave that detail to you.


Listing 1: A MySQL session storage table

mysql>CREATE TABLE SessionsTable (
    ->SID char(32) NOT NULL,
    ->expiration INT NOT NULL,
    ->value TEXT NOT NULL,
    ->PRIMARY KEY(SID) );

Listing 2 shows the MySQL handler functions. I've defined these functions in the same order in which they were introduced in the previous section. Please take some time to study the function syntax and accompanying comments.


Listing 2: The MySQL session-storage library

(<code>mysql_sessions.inc</code>)</p>

<?

// Session Table

$sess_table = "SessionsTable";

// Retrieve the session maximum lifetime (found in php.ini)

$lifetime = get_cfg_var("session.gc_maxlifetime");

//=============
// function: mysql_session_open()
// purpose: Opens a persistent server connection and selects the
//    database.
//=============

mysql_session_open($session_path, $session_name) {

  mysql_pconnect("localhost", "myusername", "mysecretpassword")
         or die("Can't connect to MySQL server! ");

  mysql_select_db("sessions_database")
         or die("Can't select MySQL sessions database");

} // end mysql_session_open()

//=============
// function: mysql_session_close()
// purpose: Doesn't actually do anything since the server connection is
//    persistent. Keep in mind that although this function
//    doesn't do anything in my particular implementation, I
//    still must define it.
//=============

mysql_session_close() {

  return 1;

} // end mysql_session_close()

//=============
// function: mysql_session_select()
// purpose: Reads the session data from the database
//=============

mysql_session_select($SID) {

  GLOBAL $sess_db;
  GLOBAL $sess_table;

  $query = "SELECT value FROM $sess_table
      WHERE SID = '$SID' AND
      expiration > ". time();

  $result = mysql_query($query);

} // end mysql_session_select()

//=============
// function: mysql_session_write()
// purpose: This function writes the session data to the database. If that SID // already exists, then the existing data will be updated.
//=============

mysql_session_write($SID, $value) {

  GLOBAL $sess_db;
  GLOBAL $sess_table;
  GLOBAL $lifetime;

  $expiration = time() + $lifetime;

  $query = "INSERT INTO $sess_table
      VALUES('$SID', '$expiration', '$value')";

  $result = mysql_query($query, $sess_db);

  if (! $result) :

   $query = "UPDATE $sess_table SET
       expiration = '$expiration',
       value = '$value' WHERE
       SID = '$SID' AND expiration >". time();

   $result = mysql_query($query, $sess_db);

  endif;

} // end mysql_session_write()

//=============
// function: mysql_session_destroy()
// purpose: deletes all session information having input SID (only one row)
//=============

mysql_session_destroy($sessionID) {

  GLOBAL $sess_table;

  $query = "DELETE FROM $sess_table
      WHERE SID = '$sessionID'";
  $result = mysql_query($query);

} // end mysql_session_destroy()

//=============
// function: mysql_session_garbage_collect()
// purpose: deletes all sessions that have expired.
//=============

mysql_session_garbage_collect($lifetime) {

  GLOBAL $sess_table;

  $query = "DELETE FROM $sess_table
      WHERE sess_expiration < ".time() - $lifetime;
  $result = mysql_query($query);

  return mysql_affected_rows($result);

} // end mysql_session_garbage_collect()

?>


Pages: 1, 2, 3

Next Pagearrow




Tagged Articles

Be the first to post this article to del.icio.us

Sponsored Resources

  • Inside Lightroom
Advertisement

Sponsored by:

O'Reilly Media

©2009, O'Reilly Media, Inc.
(707) 827-7000 / (800) 998-9938
All trademarks and registered trademarks appearing on oreilly.com are the property of their respective owners.
About O'Reilly
Academic Solutions
Authors
Contacts
Customer Service
Jobs
Newsletters
O'Reilly Labs
Press Room
Privacy Policy
RSS Feeds
Terms of Service
User Groups
Writing for O'Reilly
Content Archive
Business Technology
Computer Technology
Google
Microsoft
Mobile
Network
Operating System
Digital Photography
Programming
Software
Web
Web Design
More O'Reilly Sites
O'Reilly Radar
Ignite
Tools of Change for Publishing
Digital Media
Inside iPhone
O'Reilly FYI
makezine.com
craftzine.com
hackszine.com
perl.com
xml.com

Partner Sites
InsideRIA
java.net
O'Reilly Insights on Forbes.com