docs-session.htm 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
  2. <html>
  3. <head>
  4. <title>ADODB Session Management Manual</title>
  5. <meta http-equiv="Content-Type"
  6. content="text/html; charset=iso-8859-1">
  7. <style type="text/css">
  8. body, td {
  9. /*font-family: Arial, Helvetica, sans-serif;*/
  10. font-size: 11pt;
  11. }
  12. pre {
  13. font-size: 9pt;
  14. background-color: #EEEEEE; padding: .5em; margin: 0px;
  15. }
  16. .toplink {
  17. font-size: 8pt;
  18. }
  19. </style>
  20. </head>
  21. <body style="background-color: rgb(255, 255, 255);">
  22. <h1>ADODB Session 2 Management Manual</h1>
  23. <p>v5.20.3 01-Jan-2016<br>
  24. &copy; 2000-2013 John Lim (jlim#natsoft.com)<br>
  25. &copy; 2014 Damien Regad, Mark Newnham and the ADOdb community</p>
  26. <p> <font size="1">This software is dual licensed using BSD-Style and
  27. LGPL. This means you can use it in compiled proprietary and commercial
  28. products. </font>
  29. <p>Useful ADOdb links: <a href="http://adodb.sourceforge.net/#download">Download</a>
  30. &nbsp; <a href="http://adodb.sourceforge.net/#docs">Other Docs</a>
  31. </p>
  32. <h2>Introduction</h2>
  33. <p> This document discusses the newer session handler adodb-session2.php. If
  34. you have used the older adodb-session.php, then be forewarned that you will
  35. need to alter your session table format. Otherwise everything is <a href="#compat">backward
  36. compatible</a>.
  37. Here are the <a href="docs-session.old.htm">older
  38. docs</a> for
  39. adodb-session.php.</p>
  40. <h2>Why Session Variables in a Database? </h2>
  41. <p>We store state information specific to a user or web
  42. client in session variables. These session variables persist throughout a
  43. session, as the user moves from page to page. </p>
  44. <p>To use session variables, call session_start() at the beginning of
  45. your web page, before your HTTP headers are sent. Then for every
  46. variable you want to keep alive for the duration of the session, call
  47. variable you want to keep alive for the duration of the session, use $_SESSION['variablename'].
  48. By default, the session handler will
  49. keep track of the session by using a cookie. You can save objects or
  50. arrays in session variables also.
  51. </p>
  52. <p>The default method of storing sessions is to store it in a file.
  53. However if you have special needs such as you:
  54. </p>
  55. <ul>
  56. <li>Have multiple web servers that need to share session info</li>
  57. <li>Need to do special processing of each session</li>
  58. <li>Require notification when a session expires</li>
  59. </ul>
  60. <p>The ADOdb session handler provides you with the above
  61. additional capabilities by storing the session information as records
  62. in a database table that can be shared across multiple servers. </p>
  63. <p>These records will be garbage collected based on the php.ini [session] timeout settings.
  64. You can register a notification function to notify you when the record has expired and
  65. is about to be freed by the garbage collector.</p>
  66. <p>An alternative to using a database backed session handler is to use <a href="http://www.danga.com/memcached/">memcached</a>.
  67. This is a distributed memory based caching system suitable for storing session
  68. information.
  69. </p>
  70. <h2> The Improved Session Handler</h2>
  71. <p>In ADOdb 4.91, we added a new session handler, in adodb-session2.php.
  72. It features the following improvements:
  73. <ul>
  74. <li>Fully supports server farms using a new database table format. The
  75. previous version used the web server time for timestamps, which can cause problems
  76. on a system with multiple web servers with possibly inconsistent
  77. times. The new version uses the database server time instead for all timestamps.
  78. <li>The older database table format is obsolete. The database table must be modified
  79. to support storage of the database server time mentioned above. Also the field
  80. named DATA has been changed to SESSDATA. In some databases, DATA is a reserved
  81. word.
  82. <li>The functions dataFieldName() and syncSeconds() is obsolete.
  83. </ul>
  84. <p>Usage is
  85. <pre>
  86. include_once("adodb/session/adodb-session2.php");
  87. ADOdb_Session::config($driver, $host, $user, $password, $database,$options=false);
  88. session_start();
  89. <font
  90. color="#004040">#<br># Test session vars, the following should increment on refresh<br>#<br>$_SESSION['AVAR'] += 1;<br>print "&lt;p&gt;\$_SESSION['AVAR']={$_SESSION['AVAR']}&lt;/p&gt;";</font>
  91. </pre>
  92. <p>When the session is created in session_start( ), the global variable $<b>ADODB_SESS_CONN</b> holds
  93. the connection object.
  94. <p>The default name of the table is sessions2. If you want to override it:
  95. <pre>
  96. include_once("adodb/session/adodb-session2.php");
  97. $options['table'] = 'mytablename';
  98. ADOdb_Session::config($driver, $host, $user, $password, $database,$options);
  99. session_start();
  100. </pre>
  101. <h3>ADOdb Session Handler Features</h3>
  102. <ul>
  103. <li>Ability to define a notification function that is called when a
  104. session expires. Typically
  105. used to detect session logout and release global resources. </li>
  106. <li>Optimization of database writes. We crc32 the session data and
  107. only perform an update
  108. to the session data if there is a data change. </li>
  109. <li>Support for large amounts of session data with CLOBs (see
  110. adodb-session-clob2.php). Useful
  111. for Oracle. </li>
  112. <li>Support for encrypted session data, see
  113. adodb-cryptsession2.php. Enabling encryption is simply a matter of
  114. including adodb-cryptsession2.php instead of adodb-session2.php. </li>
  115. </ul>
  116. <h3>Session Handler Files </h3>
  117. <p>There are 3 session management files that you can use:
  118. </p>
  119. <pre>adodb-session2.php : The default<br>adodb-cryptsession2.php : Use this if you want to store encrypted session data in the database<br>adodb-session-clob2.php : Use this if you are storing DATA in clobs and you are NOT using oci8 driver</pre>
  120. <h2><strong>Usage Examples</strong></h2>
  121. <p>To force non-persistent connections, call <font color="#004040"><b>Persist</b></font>() first before session_start():
  122. <pre>
  123. <font color="#004040">
  124. include_once("adodb/session/adodb-session2.php");
  125. $driver = 'mysql'; $host = 'localhost'; $user = 'auser'; $pwd = 'secret'; $database = 'sessiondb';
  126. ADOdb_Session::config($driver, $host, $user, $password, $database, $options=false);<b><br>ADOdb_session::Persist($connectMode=false);</b>
  127. session_start();<br>
  128. # or, using DSN support so you can set other options such as port (since 5.11)
  129. include_once("adodb/session/adodb-session2.php");
  130. $dsn = 'mysql://root:pwd@localhost/mydb?persist=1&port=5654';
  131. ADOdb_Session::config($dsn, '', '', '');
  132. session_start();
  133. </font></pre>
  134. <p> The parameter to the Persist( ) method sets the connection mode. You can
  135. pass the following:</p>
  136. <table width="50%" border="1">
  137. <tr>
  138. <td><b>$connectMode</b></td>
  139. <td><b>Connection Method</b></td>
  140. </tr>
  141. <tr>
  142. <td>true</td>
  143. <td><p>PConnect( )</p></td>
  144. </tr>
  145. <tr>
  146. <td>false</td>
  147. <td>Connect( )</td>
  148. </tr>
  149. <tr>
  150. <td>'N'</td>
  151. <td>NConnect( )</td>
  152. </tr>
  153. <tr>
  154. <td>'P'</td>
  155. <td>PConnect( )</td>
  156. </tr>
  157. <tr>
  158. <td>'C'</td>
  159. <td>Connect( )</td>
  160. </tr>
  161. </table>
  162. <p>To use a encrypted sessions, simply replace the file adodb-session2.php:</p>
  163. <pre> <font
  164. color="#004040"><b><br>include('adodb/session/adodb-cryptsession2.php');</b><br>$driver = 'mysql'; $host = 'localhost'; $user = 'auser'; $pwd = 'secret'; $database = 'sessiondb';
  165. ADOdb_Session::config($driver, $host, $user, $password, $database,$options=false);<b><br>adodb_sess_open(false,false,$connectMode=false);</b>
  166. session_start();<br></font></pre>
  167. <p>And the same technique for adodb-session-clob2.php:</p>
  168. <pre> <font
  169. color="#004040"><br><b>include('adodb/session/adodb-session2-clob2.php');</b><br>$driver = 'oci8'; $host = 'localhost'; $user = 'auser'; $pwd = 'secret'; $database = 'sessiondb';
  170. ADOdb_Session::config($driver, $host, $user, $password, $database,$options=false);<b><br>adodb_sess_open(false,false,$connectMode=false);</b>
  171. session_start();</font></pre>
  172. <h2>Installation</h2>
  173. <p>1. Create this table in your database. Here is the MySQL version:
  174. <pre> <a
  175. name="sessiontab"></a> <font color="#004040">
  176. CREATE TABLE sessions2(
  177. sesskey VARCHAR( 64 ) NOT NULL DEFAULT '',
  178. expiry DATETIME NOT NULL ,
  179. expireref VARCHAR( 250 ) DEFAULT '',
  180. created DATETIME NOT NULL ,
  181. modified DATETIME NOT NULL ,
  182. sessdata LONGTEXT,
  183. PRIMARY KEY ( sesskey ) ,
  184. INDEX sess2_expiry( expiry ),
  185. INDEX sess2_expireref( expireref )
  186. )</font></pre>
  187. <p> For PostgreSQL, use:
  188. <pre>CREATE TABLE sessions2(
  189. sesskey VARCHAR( 64 ) NOT NULL DEFAULT '',
  190. expiry TIMESTAMP NOT NULL ,
  191. expireref VARCHAR( 250 ) DEFAULT '',
  192. created TIMESTAMP NOT NULL ,
  193. modified TIMESTAMP NOT NULL ,
  194. sessdata TEXT DEFAULT '',
  195. PRIMARY KEY ( sesskey )
  196. );
  197. </pre>
  198. <pre>create INDEX sess2_expiry on sessions2( expiry );
  199. create INDEX sess2_expireref on sessions2 ( expireref );</pre>
  200. <p>Here is the Oracle definition, which uses a CLOB for the SESSDATA field:
  201. <pre>
  202. <font
  203. color="#004040">CREATE TABLE SESSIONS2<br>(<br> SESSKEY VARCHAR2(48 BYTE) NOT NULL,<br> EXPIRY DATE NOT NULL,<br> EXPIREREF VARCHAR2(200 BYTE),<br> CREATED DATE NOT NULL,<br> MODIFIED DATE NOT NULL,<br> SESSDATA CLOB,<br> PRIMARY KEY(SESSKEY)<br>);
  204. <br>CREATE INDEX SESS2_EXPIRY ON SESSIONS2(EXPIRY);
  205. CREATE INDEX SESS2_EXPIREREF ON SESSIONS2(EXPIREREF);</font></pre>
  206. <p> We need to use a CLOB here because for text greater than 4000 bytes long,
  207. Oracle requires you to use the CLOB data type. If you are using the oci8 driver,
  208. ADOdb will automatically enable CLOB handling. So you can use either adodb-session2.php
  209. or adodb-session-clob2.php - in this case it doesn't matter. <br>
  210. <h2>Notifications</h2>
  211. <p>You can receive notification when your session is cleaned up by the session garbage collector or
  212. when you call session_destroy().
  213. <p>PHP's session extension will automatically run a special garbage collection function based on
  214. your php.ini session.cookie_lifetime and session.gc_probability settings. This will in turn call
  215. adodb's garbage collection function, which can be setup to do notification.
  216. <p>
  217. <pre>
  218. PHP Session --> ADOdb Session --> Find all recs --> Send --> Delete queued
  219. GC Function GC Function to be deleted notification records
  220. executed at called by for all recs
  221. random time Session Extension queued for deletion
  222. </pre>
  223. <p>When a session is created, we need to store a value in the session record (in the EXPIREREF field), typically
  224. the userid of the session. Later when the session has expired, just before the record is deleted,
  225. we reload the EXPIREREF field and call the notification function with the value of EXPIREREF, which
  226. is the userid of the person being logged off.
  227. <p>ADOdb uses a global variable $ADODB_SESSION_EXPIRE_NOTIFY that you must predefine before session
  228. start to store the notification configuration.
  229. $ADODB_SESSION_EXPIRE_NOTIFY is an array with 2 elements, the
  230. first being the name of the session variable you would like to store in
  231. the EXPIREREF field, and the 2nd is the notification function's name. </p>
  232. <p>For example, suppose we want to be notified when a user's session has expired,
  233. based on the userid. When the user logs in, we store the id in the global session variable
  234. $USERID. The function name is 'NotifyFn'.
  235. <p>
  236. So we define (before session_start() is called): </p>
  237. <pre><font color="#004040">
  238. $GLOBALS['ADODB_SESSION_EXPIRE_NOTIFY'] = array('USERID', 'NotifyFn');
  239. </font></pre>
  240. <p>And when the NotifyFn is called (when the session expires), the
  241. $EXPIREREF holding the user id is passed in as the first parameter, eg. NotifyFn($userid, $sesskey). The
  242. session key (which is the primary key of the record in the sessions
  243. table) is the 2nd parameter.</p>
  244. <p> Here is an example of a Notification function that deletes some
  245. records in the database and temporary files: </p>
  246. <pre><font color="#004040">
  247. function NotifyFn($expireref, $sesskey)
  248. {
  249. global $ADODB_SESS_CONN; # the session connection object
  250. $user = $ADODB_SESS_CONN-&gt;qstr($expireref);
  251. $ADODB_SESS_CONN-&gt;Execute("delete from shopping_cart where user=$user");
  252. system("rm /work/tmpfiles/$expireref/*");
  253. }
  254. </font></pre>
  255. <p> NOTE 1: If you have register_globals disabled in php.ini, then you
  256. will have to manually set the EXPIREREF. E.g. </p>
  257. <pre> <font color="#004040">
  258. $GLOBALS['USERID'] = GetUserID();
  259. $GLOBALS['ADODB_SESSION_EXPIRE_NOTIFY'] = array('USERID', 'NotifyFn');</font>
  260. </pre>
  261. <p> NOTE 2: If you want to change the EXPIREREF after the session
  262. record has been created, you will need to modify any session variable
  263. to force a database record update.
  264. </p>
  265. <h3>Neat Notification Tricks</h3>
  266. <p><i>ExpireRef</i> normally holds the user id of the current session.
  267. </p>
  268. <p>1. You can then write a session monitor, scanning expireref to see
  269. who is currently logged on.
  270. </p>
  271. <p>2. If you delete the sessions record for a specific user, eg.
  272. </p>
  273. <pre>delete from sessions where expireref = '$USER'<br></pre>
  274. then the user is logged out. Useful for ejecting someone from a
  275. site.
  276. <p>3. You can scan the sessions table to ensure no user
  277. can be logged in twice. Useful for security reasons.
  278. </p>
  279. <h2>Compression/Encryption Schemes</h2>
  280. Since ADOdb 4.05, thanks to Ross Smith, multiple encryption and
  281. compression schemes are supported. Currently, supported are:
  282. <p>
  283. <pre> MD5Crypt (crypt.inc.php)<br> MCrypt<br> Secure (Horde's emulation of MCrypt, if MCrypt module is not available.)<br> GZip<br> BZip2<br></pre>
  284. <p>These are stackable. E.g.
  285. <pre>ADODB_Session::filter(new ADODB_Compress_Bzip2());<br>ADODB_Session::filter(new ADODB_Encrypt_MD5());<br></pre>
  286. will compress and then encrypt the record in the database.
  287. <h2>Session Cookie Regeneration: adodb_session_regenerate_id()</h2>
  288. <p>Dynamically change the current session id with a newly generated one and update
  289. database. Currently only works with cookies. Useful to improve security by
  290. reducing the risk of session-hijacking. See this article on <a href="http://shiflett.org/articles/session-fixation">Session
  291. Fixation</a> for more info
  292. on the theory behind this feature. Usage:<pre>
  293. include('path/to/adodb/session/adodb-session2.php');
  294. session_start();
  295. # Approximately every 10 page loads, reset cookie for safety.
  296. # This is extremely simplistic example, better
  297. # to regenerate only when the user logs in or changes
  298. # user privilege levels.
  299. if ((rand()%10) == 0) adodb_session_regenerate_id();
  300. </pre>
  301. <p>This function calls session_regenerate_id() internally or simulates it if the function does not exist.
  302. <h2>Vacuum/Optimize Database</h2>
  303. <p>During session garbage collection, if postgresql is detected,
  304. ADOdb can be set to run VACUUM. If mysql is detected, then optimize database
  305. could be called.You can turn this on or off using:</p>
  306. <pre>$turnOn = true; # or false
  307. ADODB_Session::optimize($turnOn);
  308. </pre>
  309. <p>The default is optimization is disabled.</p>
  310. <h2><a name=compat></a>Backwards Compatability </h2>
  311. <p>The older method of connecting to ADOdb using global variables is still supported:</p>
  312. <pre> $ADODB_SESSION_DRIVER='mysql';
  313. $ADODB_SESSION_CONNECT='localhost';
  314. $ADODB_SESSION_USER ='root';
  315. $ADODB_SESSION_PWD ='abc';
  316. $ADODB_SESSION_DB ='phplens';
  317. include('path/to/adodb/session/adodb-<strong>session2</strong>.php'); </pre>
  318. <p>In the above example, the only things you need to change in your code to upgrade
  319. is </p>
  320. <ul>
  321. <li>your session table format to the new one.</li>
  322. <li>the include file from adodb-session.php to adodb-session2.php. </li>
  323. </ul>
  324. <h2>More Info</h2>
  325. <p>Also see the <a href="docs-adodb.htm">core ADOdb documentation</a>. And if
  326. you are interested in the obsolete adodb-session.php, see <a href="docs-session.old.htm">old
  327. session documentation</a>. </p>
  328. </body>
  329. </html>