Page 228 - Open Soource Technologies 304.indd
P. 228
Web Technologies-I
Notes session_set_save_handler(open_fn, close_fn, read_fn, write_fn, destroy_fn, gc_fn);
To make all the PHP files within a directory, use your custom session store. For this set the
following options in your httpd.conf file:
<Directory “/var/html/test”> php_value session.save_handler user php_value session.save_path
mydb php_value session.name session_store </Directory>
The mydb value should be replaced with the name of the database containing the table. It is used
by the custom session store to find the database.
The following sample code uses a MySQL database for a session store. The table used in the
example has the following structure:
CREATE TABLE session_store ( session_id char(32) not null PRIMARY KEY, expiration
timestamp, value text not null );
The first function you must provide is the open handler, which takes care of opening a new
session. It is called with the current value of session.save_path (from yourphp.ini file) and the
name of the variable containing the PHP session ID (which defaults to PHPSESSID and can be
changed in the php.ini file by setting session.name). Our open handler simply connects to the
database and sets the global variable $table to the name of the database table that holds the
session information:
function open ($save_path,$session_name)
{
global $table;
mysql_connect(‘localhost’);
mysql_select_db($save_path);
$table = $session_name; return true;
}
Once a session has been opened, the read and write handlers are called as necessary to get the
current state information and to store that state in a persistent manner. The read handler is given
the session ID, and the write handler is called with the session’s ID and the data for the session.
Our database read and write handlers query and update the database table:
function read($session_id)
{ global $table;
$result = mysql_query(“SELECT value FROM $table WHERE session_id=’$session_id’”); if($result
&& mysql_num_rows($result))
{ return mysql_result($result,0); }
else {
error_log(“read: “.mysql_error( ).”\n”,3,”/tmp/errors.log”); return “”;
} }
function write($session_id, $data)
{ global $table; $data = addslashes($data);
mysql_query(“REPLACE INTO $table (session_id,value) VALUES(‘$session_id’,’$data’)”)
or error_log(“write: “.mysql_error( ).”\n”,3,”/tmp/errors.log”); return true; }
222 LOVELY PROFESSIONAL UNIVERSITY