Advertisement
carbonize

Database Sessions

Jan 19th, 2012
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.02 KB | None | 0 0
  1. <?
  2.  
  3. mysql_connect('localhost','user','pass');
  4. mysql_select_db('mydb');
  5.  
  6.  
  7. function on_session_start($save_path, $session_name)
  8. {
  9.   error_log($session_name . ' '. session_id());
  10. }
  11.  
  12. function on_session_end()
  13. {
  14.   // Nothing needs to be done in this function
  15.   // since we used persistent connection.
  16. }
  17.  
  18. function on_session_read($key)
  19. {
  20.   error_log($key);
  21.   $stmt = 'SELECT session_data FROM sessions ';
  22.   $stmt .= "WHERE session_id='$key' ";
  23.   $stmt .= 'AND unix_timestamp(session_expiration) > unix_timestamp(date_add(now(),interval 1 hour))';
  24.   $sth = mysql_query($stmt);
  25.  
  26.   if($sth)
  27.   {
  28.     $row = mysql_fetch_array($sth);
  29.     return($row['session_data']);
  30.   }
  31.   else
  32.   {
  33.     return $sth;
  34.   }
  35. }
  36. function on_session_write($key, $val)
  37. {
  38.   error_log("$key = $value");
  39.   $val = addslashes($val);
  40.   $insert_stmt  = "INSERT INTO sessions values('$key', ";
  41.   $insert_stmt .= "'$val',unix_timestamp(date_add(now(), interval 1 hour)))";
  42.  
  43.   $update_stmt  = "UPDATE sessions SET session_data ='$val', ";
  44.   $update_stmt .= "session_expiration = unix_timestamp(date_add(now(), interval 1 hour))";
  45.   $update_stmt .= "WHERE session_id ='$key '";
  46.  
  47.   // First we try to insert, if that doesn't succeed, it means
  48.   // session is already in the table and we try to update
  49.  
  50.   mysql_query($insert_stmt);
  51.  
  52.   $err = mysql_error();
  53.  
  54.   if ($err != 0)
  55.   {
  56.     error_log( mysql_error());
  57.     mysql_query($update_stmt);
  58.   }
  59. }
  60.  
  61. function on_session_destroy($key) {
  62.   mysql_query("DELETE FROM sessions WHERE session_id = '$key'");
  63. }
  64.  
  65. function on_session_gc($max_lifetime)
  66. {
  67.   mysql_query("DELETE FROM sessions WHERE unix_timestamp(session_expiration) < unix_timestamp(now())");
  68. }
  69.  
  70.          
  71. // Set the save handlers
  72. // This will make the session functions/variables use our functions instead.
  73. session_set_save_handler("on_session_start",   "on_session_end",
  74.       "on_session_read",    "on_session_write",
  75.       "on_session_destroy", "on_session_gc");
  76.  
  77. // Carry on as if you were normal
  78. session_start();
  79. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement