source: sandbox/2.5.1-evolucao/phpgwapi/inc/adodb/docs/docs-session.htm @ 8222

Revision 8222, 15.3 KB checked in by angelo, 11 years ago (diff)

Ticket #3491 - Compatibilizar Expresso com novas versoes do PHP

  • Property svn:eol-style set to native
  • Property svn:executable set to *
Line 
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">
8body, td {
9/*font-family: Arial, Helvetica, sans-serif;*/
10font-size: 11pt;
11}
12pre {
13font-size: 9pt;
14background-color: #EEEEEE; padding: .5em; margin: 0px;
15}
16.toplink {
17font-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>
24V5.18 3 Sep 2012  (c) 2000-2012 John Lim (jlim#natsoft.com)
25</p>
26<p> <font size="1">This software is dual licensed using BSD-Style and
27LGPL. This means you can use it in compiled proprietary and commercial
28products. </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
43session, as the user moves from page to page. </p>
44<p>To use session variables, call session_start() at the beginning of
45your web page, before your HTTP headers are sent. Then for every
46variable you want to keep alive for the duration of the session, call
47variable you want to keep alive for the duration of the session, use $_SESSION['variablename'].
48 By default, the session handler will
49keep track of the session by using a cookie. You can save objects or
50arrays in session variables also.
51</p>
52<p>The default method of storing sessions is to store it in a file.
53However 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
61additional capabilities by storing the session information as records
62in 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.
64You can register a notification function to notify you when the record has expired and
65is 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.
72It 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
85<p>Usage is
86
87<pre>
88include_once("adodb/session/adodb-session2.php");
89ADOdb_Session::config($driver, $host, $user, $password, $database,$options=false);
90session_start();
91
92<font
93 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>
94</pre>
95
96<p>When the session is created in session_start( ), the global variable $<b>ADODB_SESS_CONN</b> holds
97the connection object.
98<p>The default name of the table is sessions2. If you want to override it:
99 
100<pre>
101include_once("adodb/session/adodb-session2.php");
102$options['table'] = 'mytablename';
103ADOdb_Session::config($driver, $host, $user, $password, $database,$options);
104session_start();
105</pre>
106
107
108<h3>ADOdb Session Handler Features</h3>
109<ul>
110  <li>Ability to define a notification function that is called when a
111session expires. Typically
112used to detect session logout and release global resources. </li>
113  <li>Optimization of database writes. We crc32 the session data and
114only perform an update
115to the session data if there is a data change. </li>
116  <li>Support for large amounts of session data with CLOBs (see
117adodb-session-clob2.php). Useful
118for Oracle. </li>
119  <li>Support for encrypted session data, see
120adodb-cryptsession2.php. Enabling encryption is simply a matter of
121including adodb-cryptsession2.php instead of adodb-session2.php. </li>
122</ul>
123<h3>Session Handler Files </h3>
124<p>There are 3 session management files that you can use:
125</p>
126<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>
127<h2><strong>Usage Examples</strong></h2>
128<p>To force non-persistent connections, call <font color="#004040"><b>Persist</b></font>() first before session_start():
129
130 
131<pre>
132 <font color="#004040">
133include_once("adodb/session/adodb-session2.php");
134$driver = 'mysql'; $host = 'localhost'; $user = 'auser'; $pwd = 'secret'; $database = 'sessiondb';
135ADOdb_Session::config($driver, $host, $user, $password, $database, $options=false);<b><br>ADOdb_session::Persist($connectMode=false);</b>
136session_start();<br>
137
138# or, using DSN support so you can set other options such as port (since 5.11)
139include_once("adodb/session/adodb-session2.php");
140$dsn = 'mysql://root:pwd@localhost/mydb?persist=1&port=5654';
141ADOdb_Session::config($dsn, '', '', '');
142session_start();
143</font></pre>
144<p> The parameter to the Persist( ) method sets the connection mode. You can
145  pass the following:</p>
146<table width="50%" border="1">
147  <tr>
148    <td><b>$connectMode</b></td>
149    <td><b>Connection Method</b></td>
150  </tr>
151  <tr>
152    <td>true</td>
153    <td><p>PConnect( )</p></td>
154  </tr>
155  <tr>
156    <td>false</td>
157    <td>Connect( )</td>
158  </tr>
159  <tr>
160    <td>'N'</td>
161    <td>NConnect( )</td>
162  </tr>
163  <tr>
164    <td>'P'</td>
165    <td>PConnect( )</td>
166  </tr>
167  <tr>
168    <td>'C'</td>
169    <td>Connect( )</td>
170  </tr>
171</table>
172<p>To use a encrypted sessions, simply replace the file adodb-session2.php:</p>
173 <pre> <font
174 color="#004040"><b><br>include('adodb/session/adodb-cryptsession2.php');</b><br>$driver = 'mysql'; $host = 'localhost'; $user = 'auser'; $pwd = 'secret'; $database = 'sessiondb';
175ADOdb_Session::config($driver, $host, $user, $password, $database,$options=false);<b><br>adodb_sess_open(false,false,$connectMode=false);</b>
176session_start();<br></font></pre>
177 <p>And the same technique for adodb-session-clob2.php:</p>
178 <pre>  <font
179 color="#004040"><br><b>include('adodb/session/adodb-session2-clob2.php');</b><br>$driver = 'oci8'; $host = 'localhost'; $user = 'auser'; $pwd = 'secret'; $database = 'sessiondb';
180ADOdb_Session::config($driver, $host, $user, $password, $database,$options=false);<b><br>adodb_sess_open(false,false,$connectMode=false);</b>
181session_start();</font></pre>
182 <h2>Installation</h2>
183<p>1. Create this table in your database. Here is the MySQL version:
184<pre> <a
185 name="sessiontab"></a> <font color="#004040">
186CREATE TABLE sessions2(
187          sesskey VARCHAR( 64 ) NOT NULL DEFAULT '',
188          expiry DATETIME NOT NULL ,
189          expireref VARCHAR( 250 ) DEFAULT '',
190          created DATETIME NOT NULL ,
191          modified DATETIME NOT NULL ,
192          sessdata LONGTEXT,
193          PRIMARY KEY ( sesskey ) ,
194          INDEX sess2_expiry( expiry ),
195          INDEX sess2_expireref( expireref )
196)</font></pre>
197
198 <p> For PostgreSQL, use:
199 <pre>CREATE TABLE sessions2(
200 sesskey VARCHAR( 64 ) NOT NULL DEFAULT '',
201 expiry TIMESTAMP NOT NULL ,
202 expireref VARCHAR( 250 ) DEFAULT '',
203 created TIMESTAMP NOT NULL ,
204 modified TIMESTAMP NOT NULL ,
205 sessdata TEXT DEFAULT '',
206 PRIMARY KEY ( sesskey )
207 );
208</pre>
209 <pre>create INDEX sess2_expiry on sessions2( expiry );
210create INDEX sess2_expireref on sessions2 ( expireref );</pre>
211 <p>Here is the Oracle definition, which uses a CLOB for the SESSDATA field:
212 <pre>
213  <font
214 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>);
215<br>CREATE INDEX SESS2_EXPIRY ON SESSIONS2(EXPIRY);
216CREATE INDEX SESS2_EXPIREREF ON SESSIONS2(EXPIREREF);</font></pre>
217<p> We need to use a CLOB here because for text greater than 4000 bytes long,
218  Oracle requires you to use the CLOB data type. If you are using the oci8 driver,
219  ADOdb will automatically enable CLOB handling. So you can use either adodb-session2.php
220  or adodb-session-clob2.php - in this case it doesn't matter. <br>   
221<h2>Notifications</h2>
222<p>You can receive notification when your session is cleaned up by the session garbage collector or
223when you call session_destroy().
224<p>PHP's session extension will automatically run a special garbage collection function based on
225your php.ini session.cookie_lifetime and session.gc_probability settings. This will in turn call
226adodb's garbage collection function, which can be setup to do notification.
227<p>
228<pre>
229        PHP Session --> ADOdb Session  --> Find all recs  --> Send          --> Delete queued
230        GC Function     GC Function        to be deleted      notification      records
231        executed at     called by                             for all recs
232        random time     Session Extension                     queued for deletion
233</pre>
234<p>When a session is created, we need to store a value in the session record (in the EXPIREREF field), typically
235the userid of the session. Later when the session has expired,  just before the record is deleted,
236we reload the EXPIREREF field and call the notification function with the value of EXPIREREF, which
237is the userid of the person being logged off.
238<p>ADOdb uses a global variable $ADODB_SESSION_EXPIRE_NOTIFY that you must predefine before session
239start to store the notification configuration.
240$ADODB_SESSION_EXPIRE_NOTIFY is an array with 2 elements, the
241first being the name of the session variable you would like to store in
242the EXPIREREF field, and the 2nd is the notification function's name. </p>
243<p>For example, suppose we want to be notified when a user's session has expired,
244based on the userid. When the user logs in, we store the id in the global session variable
245$USERID. The function name is 'NotifyFn'.
246<p>
247So we define (before session_start() is called): </p>
248<pre> <font color="#004040">
249        $ADODB_SESSION_EXPIRE_NOTIFY = array('USERID','NotifyFn');
250</font></pre>
251And when the NotifyFn is called (when the session expires), the
252$EXPIREREF holding the user id is passed in as the first parameter, eg. NotifyFn($userid, $sesskey). The
253session key (which is the primary key of the record in the sessions
254table) is the 2nd parameter.
255<p> Here is an example of a Notification function that deletes some
256records in the database and temporary files: </p>
257<pre><font color="#004040">
258        function NotifyFn($expireref, $sesskey)
259        {
260                global $ADODB_SESS_CONN; # the session connection object
261                $user = $ADODB_SESS_CONN-&gt;qstr($expireref);
262               
263                $ADODB_SESS_CONN-&gt;Execute("delete from shopping_cart where user=$user");         
264                system("rm /work/tmpfiles/$expireref/*");
265        }</font> 
266                          </pre>
267<p> NOTE 1: If you have register_globals disabled in php.ini, then you
268will have to manually set the EXPIREREF. E.g. </p>
269<pre> <font color="#004040">
270$GLOBALS['USERID'] = GetUserID();
271$ADODB_SESSION_EXPIRE_NOTIFY = array('USERID','NotifyFn');</font>
272</pre>
273<p> NOTE 2: If you want to change the EXPIREREF after the session
274record has been created, you will need to modify any session variable
275to force a database record update.
276</p>
277<h3>Neat Notification Tricks</h3>
278<p><i>ExpireRef</i> normally holds the user id of the current session.
279</p>
280<p>1. You can then write a session monitor, scanning expireref to see
281who is currently logged on.
282</p>
283<p>2. If you delete the sessions record for a specific user, eg.
284</p>
285<pre>delete from sessions where expireref = '$USER'<br></pre>
286then the user is logged out. Useful for ejecting someone from a
287site.
288<p>3. You can scan the sessions table to ensure no user
289can be logged in twice. Useful for security reasons.
290</p>
291<h2>Compression/Encryption Schemes</h2>
292Since ADOdb 4.05, thanks to Ross Smith, multiple encryption and
293compression schemes are supported. Currently, supported are:
294<p>
295<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>
296<p>These are stackable. E.g.
297<pre>ADODB_Session::filter(new ADODB_Compress_Bzip2());<br>ADODB_Session::filter(new ADODB_Encrypt_MD5());<br></pre>
298will compress and then encrypt the record in the database.
299<h2>Session Cookie Regeneration: adodb_session_regenerate_id()</h2>
300<p>Dynamically change the current session id with a newly generated one and update
301  database. Currently only works with cookies. Useful to improve security by
302  reducing the risk of session-hijacking. See this article on <a href=http://shiflett.org/articles/security-corner-feb2004>Session
303  Fixation</a> for more info
304on the theory behind this feature. Usage:<pre>
305        include('path/to/adodb/session/adodb-session2.php');
306       
307        session_start();
308        # Approximately every 10 page loads, reset cookie for safety.
309        # This is extremely simplistic example, better
310        # to regenerate only when the user logs in or changes
311        # user privilege levels.
312        if ((rand()%10) == 0) adodb_session_regenerate_id();
313</pre>
314<p>This function calls session_regenerate_id() internally or simulates it if the function does not exist.
315<h2>Vacuum/Optimize Database</h2>
316<p>During session garbage collection, if postgresql is detected,
317  ADOdb can be set to run VACUUM. If mysql is detected, then optimize database
318  could be called.You can turn this on or off using:</p>
319<pre>$turnOn = true; # or false
320ADODB_Session::optimize($turnOn);
321</pre>
322<p>The default  is optimization is disabled.</p>
323<h2><a name=compat></a>Backwards Compatability </h2>
324<p>The older method of connecting to ADOdb using global variables is still supported:</p>
325<pre> $ADODB_SESSION_DRIVER='mysql';
326 $ADODB_SESSION_CONNECT='localhost';
327 $ADODB_SESSION_USER ='root';
328 $ADODB_SESSION_PWD ='abc';
329 $ADODB_SESSION_DB ='phplens';
330 
331 include('path/to/adodb/session/adodb-<strong>session2</strong>.php'); </pre>
332<p>In the above example, the only things you need to change in your code to upgrade
333  is </p>
334<ul>
335  <li>your session table format to the new one.</li>
336  <li>the include file from adodb-session.php to adodb-session2.php. </li>
337</ul>
338<h2>More Info</h2>
339<p>Also see the <a href="docs-adodb.htm">core ADOdb documentation</a>. And if
340  you are interested in the obsolete adodb-session.php, see <a href="docs-session.old.htm">old
341    session documentation</a>. </p>
342</body>
343</html>
Note: See TracBrowser for help on using the repository browser.