home *** CD-ROM | disk | FTP | other *** search
/ Enter 2004 June / ENTER.ISO / files / xampp-win32-1.4.5-installer.exe / xampp / adodb-session-clob.php < prev    next >
Encoding:
PHP Script  |  2004-03-20  |  14.5 KB  |  445 lines

  1. <?php
  2. /*
  3.   V4.21 20 Mar 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
  4.   Released under both BSD license and Lesser GPL library license. 
  5.   Whenever there is any discrepancy between the two licenses, 
  6.   the BSD license will take precedence.
  7.       Set tabs to 4 for best viewing.
  8.   
  9.   Latest version of ADODB is available at http://php.weblogs.com/adodb
  10.   ======================================================================
  11.   
  12.  This file provides PHP4 session management using the ADODB database
  13.  wrapper library, using Oracle CLOB's to store data. Contributed by achim.gosse@ddd.de.
  14.  
  15.  Example
  16.  =======
  17.  
  18.      GLOBAL $HTTP_SESSION_VARS;
  19.     include('adodb.inc.php');
  20.     include('adodb-session.php');
  21.     session_start();
  22.     session_register('AVAR');
  23.     $HTTP_SESSION_VARS['AVAR'] += 1;
  24.     print "<p>\$HTTP_SESSION_VARS['AVAR']={$HTTP_SESSION_VARS['AVAR']}</p>";
  25.     
  26. To force non-persistent connections, call adodb_session_open first before session_start():
  27.  
  28.      GLOBAL $HTTP_SESSION_VARS;
  29.     include('adodb.inc.php');
  30.     include('adodb-session.php');
  31.     adodb_session_open(false,false,false);
  32.     session_start();
  33.     session_register('AVAR');
  34.     $HTTP_SESSION_VARS['AVAR'] += 1;
  35.     print "<p>\$HTTP_SESSION_VARS['AVAR']={$HTTP_SESSION_VARS['AVAR']}</p>";
  36.  
  37.  
  38.  Installation
  39.  ============
  40.  1. Create this table in your database (syntax might vary depending on your db):
  41.  
  42.   create table sessions (
  43.        SESSKEY char(32) not null,
  44.        EXPIRY int(11) unsigned not null,
  45.        EXPIREREF varchar(64),
  46.        DATA CLOB,
  47.       primary key (sesskey)
  48.   );
  49.  
  50.  
  51.   2. Then define the following parameters in this file:
  52.       $ADODB_SESSION_DRIVER='database driver, eg. mysql or ibase';
  53.     $ADODB_SESSION_CONNECT='server to connect to';
  54.     $ADODB_SESSION_USER ='user';
  55.     $ADODB_SESSION_PWD ='password';
  56.     $ADODB_SESSION_DB ='database';
  57.     $ADODB_SESSION_TBL = 'sessions'
  58.     $ADODB_SESSION_USE_LOBS = false; (or, if you wanna use CLOBS (= 'CLOB') or ( = 'BLOB')
  59.     
  60.   3. Recommended is PHP 4.0.6 or later. There are documented
  61.      session bugs in earlier versions of PHP.
  62.  
  63.   4. If you want to receive notifications when a session expires, then
  64.        you can tag a session with an EXPIREREF, and before the session
  65.      record is deleted, we can call a function that will pass the EXPIREREF
  66.      as the first parameter, and the session key as the second parameter.
  67.      
  68.      To do this, define a notification function, say NotifyFn:
  69.      
  70.          function NotifyFn($expireref, $sesskey)
  71.          {
  72.          }
  73.      
  74.      Then you need to define a global variable $ADODB_SESSION_EXPIRE_NOTIFY.
  75.      This is an array with 2 elements, the first being the name of the variable
  76.      you would like to store in the EXPIREREF field, and the 2nd is the 
  77.      notification function's name.
  78.      
  79.      In this example, we want to be notified when a user's session 
  80.      has expired, so we store the user id in the global variable $USERID, 
  81.      store this value in the EXPIREREF field:
  82.      
  83.          $ADODB_SESSION_EXPIRE_NOTIFY = array('USERID','NotifyFn');
  84.         
  85.     Then when the NotifyFn is called, we are passed the $USERID as the first
  86.     parameter, eg. NotifyFn($userid, $sesskey).
  87. */
  88.  
  89. if (!defined('_ADODB_LAYER')) {
  90.     include (dirname(__FILE__).'/adodb.inc.php');
  91. }
  92.  
  93. if (!defined('ADODB_SESSION')) {
  94.  
  95.  define('ADODB_SESSION',1);
  96.  
  97.  /* if database time and system time is difference is greater than this, then give warning */
  98.  define('ADODB_SESSION_SYNCH_SECS',60); 
  99.  
  100. /****************************************************************************************\
  101.     Global definitions
  102. \****************************************************************************************/
  103. GLOBAL     $ADODB_SESSION_CONNECT, 
  104.     $ADODB_SESSION_DRIVER,
  105.     $ADODB_SESSION_USER,
  106.     $ADODB_SESSION_PWD,
  107.     $ADODB_SESSION_DB,
  108.     $ADODB_SESS_CONN,
  109.     $ADODB_SESS_LIFE,
  110.     $ADODB_SESS_DEBUG,
  111.     $ADODB_SESSION_EXPIRE_NOTIFY,
  112.     $ADODB_SESSION_CRC,
  113.     $ADODB_SESSION_USE_LOBS,
  114.     $ADODB_SESSION_TBL;
  115.     
  116.     if (!isset($ADODB_SESSION_USE_LOBS)) $ADODB_SESSION_USE_LOBS = 'CLOB';
  117.     
  118.     $ADODB_SESS_LIFE = ini_get('session.gc_maxlifetime');
  119.     if ($ADODB_SESS_LIFE <= 1) {
  120.      // bug in PHP 4.0.3 pl 1  -- how about other versions?
  121.      //print "<h3>Session Error: PHP.INI setting <i>session.gc_maxlifetime</i>not set: $ADODB_SESS_LIFE</h3>";
  122.          $ADODB_SESS_LIFE=1440;
  123.     }
  124.     $ADODB_SESSION_CRC = false;
  125.     //$ADODB_SESS_DEBUG = true;
  126.     
  127.     //////////////////////////////////
  128.     /* SET THE FOLLOWING PARAMETERS */
  129.     //////////////////////////////////
  130.     
  131.     if (empty($ADODB_SESSION_DRIVER)) {
  132.         $ADODB_SESSION_DRIVER='mysql';
  133.         $ADODB_SESSION_CONNECT='localhost';
  134.         $ADODB_SESSION_USER ='root';
  135.         $ADODB_SESSION_PWD ='';
  136.         $ADODB_SESSION_DB ='xphplens_2';
  137.     }
  138.     
  139.     if (empty($ADODB_SESSION_EXPIRE_NOTIFY)) {
  140.         $ADODB_SESSION_EXPIRE_NOTIFY = false;
  141.     }
  142.     //  Made table name configurable - by David Johnson djohnson@inpro.net
  143.     if (empty($ADODB_SESSION_TBL)){
  144.         $ADODB_SESSION_TBL = 'sessions';
  145.     }
  146.     
  147.  
  148.     // defaulting $ADODB_SESSION_USE_LOBS
  149.     if (!isset($ADODB_SESSION_USE_LOBS) || empty($ADODB_SESSION_USE_LOBS)) {
  150.         $ADODB_SESSION_USE_LOBS = false;
  151.     }
  152.  
  153.     /*
  154.     $ADODB_SESS['driver'] = $ADODB_SESSION_DRIVER;
  155.     $ADODB_SESS['connect'] = $ADODB_SESSION_CONNECT;
  156.     $ADODB_SESS['user'] = $ADODB_SESSION_USER;
  157.     $ADODB_SESS['pwd'] = $ADODB_SESSION_PWD;
  158.     $ADODB_SESS['db'] = $ADODB_SESSION_DB;
  159.     $ADODB_SESS['life'] = $ADODB_SESS_LIFE;
  160.     $ADODB_SESS['debug'] = $ADODB_SESS_DEBUG;
  161.     
  162.     $ADODB_SESS['debug'] = $ADODB_SESS_DEBUG;
  163.     $ADODB_SESS['table'] = $ADODB_SESS_TBL;
  164.     */
  165.     
  166. /****************************************************************************************\
  167.     Create the connection to the database. 
  168.     
  169.     If $ADODB_SESS_CONN already exists, reuse that connection
  170. \****************************************************************************************/
  171. function adodb_sess_open($save_path, $session_name,$persist=true) 
  172. {
  173. GLOBAL $ADODB_SESS_CONN;
  174.     if (isset($ADODB_SESS_CONN)) return true;
  175.     
  176. GLOBAL     $ADODB_SESSION_CONNECT, 
  177.     $ADODB_SESSION_DRIVER,
  178.     $ADODB_SESSION_USER,
  179.     $ADODB_SESSION_PWD,
  180.     $ADODB_SESSION_DB,
  181.     $ADODB_SESS_DEBUG;
  182.     
  183.     // cannot use & below - do not know why...
  184.     $ADODB_SESS_CONN = ADONewConnection($ADODB_SESSION_DRIVER);
  185.     if (!empty($ADODB_SESS_DEBUG)) {
  186.         $ADODB_SESS_CONN->debug = true;
  187.         ADOConnection::outp( " conn=$ADODB_SESSION_CONNECT user=$ADODB_SESSION_USER pwd=$ADODB_SESSION_PWD db=$ADODB_SESSION_DB ");
  188.     }
  189.     if ($persist) $ok = $ADODB_SESS_CONN->PConnect($ADODB_SESSION_CONNECT,
  190.             $ADODB_SESSION_USER,$ADODB_SESSION_PWD,$ADODB_SESSION_DB);
  191.     else $ok = $ADODB_SESS_CONN->Connect($ADODB_SESSION_CONNECT,
  192.             $ADODB_SESSION_USER,$ADODB_SESSION_PWD,$ADODB_SESSION_DB);
  193.     
  194.     if (!$ok) ADOConnection::outp( "<p>Session: connection failed</p>",false);
  195. }
  196.  
  197. /****************************************************************************************\
  198.     Close the connection
  199. \****************************************************************************************/
  200. function adodb_sess_close() 
  201. {
  202. global $ADODB_SESS_CONN;
  203.  
  204.     if ($ADODB_SESS_CONN) $ADODB_SESS_CONN->Close();
  205.     return true;
  206. }
  207.  
  208. /****************************************************************************************\
  209.     Slurp in the session variables and return the serialized string
  210. \****************************************************************************************/
  211. function adodb_sess_read($key) 
  212. {
  213. global $ADODB_SESS_CONN,$ADODB_SESSION_TBL,$ADODB_SESSION_CRC;
  214.  
  215.     $rs = $ADODB_SESS_CONN->Execute("SELECT data FROM $ADODB_SESSION_TBL WHERE sesskey = '$key' AND expiry >= " . time());
  216.     if ($rs) {
  217.         if ($rs->EOF) {
  218.             $v = '';
  219.         } else 
  220.             $v = rawurldecode(reset($rs->fields));
  221.             
  222.         $rs->Close();
  223.         
  224.         // new optimization adodb 2.1
  225.         $ADODB_SESSION_CRC = strlen($v).crc32($v);
  226.         
  227.         return $v;
  228.     }
  229.     
  230.     return ''; // thx to Jorma Tuomainen, webmaster#wizactive.com
  231. }
  232.  
  233. /****************************************************************************************\
  234.     Write the serialized data to a database.
  235.     
  236.     If the data has not been modified since adodb_sess_read(), we do not write.
  237. \****************************************************************************************/
  238. function adodb_sess_write($key, $val) 
  239. {
  240.     global
  241.         $ADODB_SESS_CONN, 
  242.         $ADODB_SESS_LIFE, 
  243.         $ADODB_SESSION_TBL,
  244.         $ADODB_SESS_DEBUG, 
  245.         $ADODB_SESSION_CRC,
  246.         $ADODB_SESSION_EXPIRE_NOTIFY,
  247.         $ADODB_SESSION_DRIVER,            // added
  248.         $ADODB_SESSION_USE_LOBS;        // added
  249.  
  250.     $expiry = time() + $ADODB_SESS_LIFE;
  251.     
  252.     // crc32 optimization since adodb 2.1
  253.     // now we only update expiry date, thx to sebastian thom in adodb 2.32
  254.     if ($ADODB_SESSION_CRC !== false && $ADODB_SESSION_CRC == strlen($val).crc32($val)) {
  255.         if ($ADODB_SESS_DEBUG) echo "<p>Session: Only updating date - crc32 not changed</p>";
  256.         $qry = "UPDATE $ADODB_SESSION_TBL SET expiry=$expiry WHERE sesskey='$key' AND expiry >= " . time();
  257.         $rs = $ADODB_SESS_CONN->Execute($qry);    
  258.         return true;
  259.     }
  260.     $val = rawurlencode($val);
  261.     
  262.     $arr = array('sesskey' => $key, 'expiry' => $expiry, 'data' => $val);
  263.     if ($ADODB_SESSION_EXPIRE_NOTIFY) {
  264.         $var = reset($ADODB_SESSION_EXPIRE_NOTIFY);
  265.         global $$var;
  266.         $arr['expireref'] = $$var;
  267.     }
  268.  
  269.     
  270.     if ($ADODB_SESSION_USE_LOBS === false) {    // no lobs, simply use replace()
  271.         $rs = $ADODB_SESS_CONN->Replace($ADODB_SESSION_TBL,$arr, 'sesskey',$autoQuote = true);
  272.         if (!$rs) {
  273.             $err = $ADODB_SESS_CONN->ErrorMsg();
  274.         }
  275.     } else {
  276.         // what value shall we insert/update for lob row?
  277.         switch ($ADODB_SESSION_DRIVER) {
  278.             // empty_clob or empty_lob for oracle dbs
  279.             case "oracle":
  280.             case "oci8":
  281.             case "oci8po":
  282.             case "oci805":
  283.                 $lob_value = sprintf("empty_%s()", strtolower($ADODB_SESSION_USE_LOBS));
  284.                 break;
  285.  
  286.             // null for all other
  287.             default:
  288.                 $lob_value = "null";
  289.                 break;
  290.         }
  291.  
  292.         // do we insert or update? => as for sesskey
  293.         $res = $ADODB_SESS_CONN->Execute("select count(*) as cnt from $ADODB_SESSION_TBL where sesskey = '$key'");
  294.         if ($res && reset($res->fields) > 0) {
  295.             $qry = sprintf("update %s set expiry = %d, data = %s where sesskey = '%s'", $ADODB_SESSION_TBL, $expiry, $lob_value, $key);
  296.         } else {
  297.             // insert
  298.             $qry = sprintf("insert into %s (sesskey, expiry, data) values ('%s', %d, %s)", $ADODB_SESSION_TBL, $key, $expiry, $lob_value);
  299.         }
  300.  
  301.         $err = "";
  302.         $rs1 = $ADODB_SESS_CONN->Execute($qry);
  303.         if (!$rs1) {
  304.             $err .= $ADODB_SESS_CONN->ErrorMsg()."\n";
  305.         }
  306.         $rs2 = $ADODB_SESS_CONN->UpdateBlob($ADODB_SESSION_TBL, 'data', $val, "sesskey='$key'", strtoupper($ADODB_SESSION_USE_LOBS));
  307.         if (!$rs2) {
  308.             $err .= $ADODB_SESS_CONN->ErrorMsg()."\n";
  309.         }
  310.         $rs = ($rs1 && $rs2) ? true : false;
  311.     }
  312.  
  313.     if (!$rs) {
  314.         ADOConnection::outp( '<p>Session Replace: '.nl2br($err).'</p>',false);
  315.     }  else {
  316.         // bug in access driver (could be odbc?) means that info is not commited
  317.         // properly unless select statement executed in Win2000
  318.         if ($ADODB_SESS_CONN->databaseType == 'access') 
  319.             $rs = $ADODB_SESS_CONN->Execute("select sesskey from $ADODB_SESSION_TBL WHERE sesskey='$key'");
  320.     }
  321.     return !empty($rs);
  322. }
  323.  
  324. function adodb_sess_destroy($key) 
  325. {
  326.     global $ADODB_SESS_CONN, $ADODB_SESSION_TBL,$ADODB_SESSION_EXPIRE_NOTIFY;
  327.     
  328.     if ($ADODB_SESSION_EXPIRE_NOTIFY) {
  329.         reset($ADODB_SESSION_EXPIRE_NOTIFY);
  330.         $fn = next($ADODB_SESSION_EXPIRE_NOTIFY);
  331.         $savem = $ADODB_SESS_CONN->SetFetchMode(ADODB_FETCH_NUM);
  332.         $rs = $ADODB_SESS_CONN->Execute("SELECT expireref,sesskey FROM $ADODB_SESSION_TBL WHERE sesskey='$key'");
  333.         $ADODB_SESS_CONN->SetFetchMode($savem);
  334.         if ($rs) {
  335.             $ADODB_SESS_CONN->BeginTrans();
  336.             while (!$rs->EOF) {
  337.                 $ref = $rs->fields[0];
  338.                 $key = $rs->fields[1];
  339.                 $fn($ref,$key);
  340.                 $del = $ADODB_SESS_CONN->Execute("DELETE FROM $ADODB_SESSION_TBL WHERE sesskey='$key'");
  341.                 $rs->MoveNext();
  342.             }
  343.             $ADODB_SESS_CONN->CommitTrans();
  344.         }
  345.     } else {
  346.         $qry = "DELETE FROM $ADODB_SESSION_TBL WHERE sesskey = '$key'";
  347.         $rs = $ADODB_SESS_CONN->Execute($qry);
  348.     }
  349.     return $rs ? true : false;
  350. }
  351.  
  352. function adodb_sess_gc($maxlifetime) 
  353. {
  354.     global $ADODB_SESS_DEBUG, $ADODB_SESS_CONN, $ADODB_SESSION_TBL,$ADODB_SESSION_EXPIRE_NOTIFY;
  355.     
  356.     if ($ADODB_SESSION_EXPIRE_NOTIFY) {
  357.         reset($ADODB_SESSION_EXPIRE_NOTIFY);
  358.         $fn = next($ADODB_SESSION_EXPIRE_NOTIFY);
  359.         $savem = $ADODB_SESS_CONN->SetFetchMode(ADODB_FETCH_NUM);
  360.         $t = time();
  361.         $rs = $ADODB_SESS_CONN->Execute("SELECT expireref,sesskey FROM $ADODB_SESSION_TBL WHERE expiry < $t");
  362.         $ADODB_SESS_CONN->SetFetchMode($savem);
  363.         if ($rs) {
  364.             $ADODB_SESS_CONN->BeginTrans();
  365.             while (!$rs->EOF) {
  366.                 $ref = $rs->fields[0];
  367.                 $key = $rs->fields[1];
  368.                 $fn($ref,$key);
  369.                 $del = $ADODB_SESS_CONN->Execute("DELETE FROM $ADODB_SESSION_TBL WHERE sesskey='$key'");
  370.                 $rs->MoveNext();
  371.             }
  372.             $rs->Close();
  373.             
  374.             //$ADODB_SESS_CONN->Execute("DELETE FROM $ADODB_SESSION_TBL WHERE expiry < $t");
  375.             $ADODB_SESS_CONN->CommitTrans();
  376.             
  377.         }
  378.     } else {
  379.         $ADODB_SESS_CONN->Execute("DELETE FROM $ADODB_SESSION_TBL WHERE expiry < " . time());
  380.     
  381.         if ($ADODB_SESS_DEBUG) ADOConnection::outp("<p><b>Garbage Collection</b>: $qry</p>");
  382.     }
  383.     // suggested by Cameron, "GaM3R" <gamr@outworld.cx>
  384.     if (defined('ADODB_SESSION_OPTIMIZE')) {
  385.     global $ADODB_SESSION_DRIVER;
  386.     
  387.         switch( $ADODB_SESSION_DRIVER ) {
  388.             case 'mysql':
  389.             case 'mysqlt':
  390.                 $opt_qry = 'OPTIMIZE TABLE '.$ADODB_SESSION_TBL;
  391.                 break;
  392.             case 'postgresql':
  393.             case 'postgresql7':
  394.                 $opt_qry = 'VACUUM '.$ADODB_SESSION_TBL;    
  395.                 break;
  396.         }
  397.         if (!empty($opt_qry)) {
  398.             $ADODB_SESS_CONN->Execute($opt_qry);
  399.         }
  400.     }
  401.     if ($ADODB_SESS_CONN->dataProvider === 'oci8') $sql = 'select  TO_CHAR('.($ADODB_SESS_CONN->sysTimeStamp).', \'RRRR-MM-DD HH24:MI:SS\') from '. $ADODB_SESSION_TBL;
  402.     else $sql = 'select '.$ADODB_SESS_CONN->sysTimeStamp.' from '. $ADODB_SESSION_TBL;
  403.     
  404.     $rs =& $ADODB_SESS_CONN->SelectLimit($sql,1);
  405.     if ($rs && !$rs->EOF) {
  406.     
  407.         $dbts = reset($rs->fields);
  408.         $rs->Close();
  409.         $dbt = $ADODB_SESS_CONN->UnixTimeStamp($dbts);
  410.         $t = time();
  411.         if (abs($dbt - $t) >= ADODB_SESSION_SYNCH_SECS) {
  412.         global $HTTP_SERVER_VARS;
  413.             $msg = 
  414.             __FILE__.": Server time for webserver {$HTTP_SERVER_VARS['HTTP_HOST']} not in synch with database: database=$dbt ($dbts), webserver=$t (diff=".(abs($dbt-$t)/3600)." hrs)";
  415.             error_log($msg);
  416.             if ($ADODB_SESS_DEBUG) ADOConnection::outp("<p>$msg</p>");
  417.         }
  418.     }
  419.     
  420.     return true;
  421. }
  422.  
  423. session_module_name('user'); 
  424. session_set_save_handler(
  425.     "adodb_sess_open",
  426.     "adodb_sess_close",
  427.     "adodb_sess_read",
  428.     "adodb_sess_write",
  429.     "adodb_sess_destroy",
  430.     "adodb_sess_gc");
  431. }
  432.  
  433. /*  TEST SCRIPT -- UNCOMMENT */
  434.  
  435. if (0) {
  436. GLOBAL $HTTP_SESSION_VARS;
  437.  
  438.     session_start();
  439.     session_register('AVAR');
  440.     $HTTP_SESSION_VARS['AVAR'] += 1;
  441.     ADOConnection::outp( "<p>\$HTTP_SESSION_VARS['AVAR']={$HTTP_SESSION_VARS['AVAR']}</p>",false);
  442. }
  443.  
  444. ?>
  445.