05.05.2013 Views

Programming PHP

Programming PHP

Programming PHP

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

php.ini file) and the name of the variable containing the <strong>PHP</strong> session ID (which<br />

defaults to <strong>PHP</strong>SESSID and can be changed in the php.ini file by setting session.name).<br />

Our open handler simply connects to the database and sets the global variable $table<br />

to the name of the database table that holds the session information:<br />

function open ($save_path,$session_name) {<br />

global $table;<br />

mysql_connect('localhost');<br />

mysql_select_db($save_path);<br />

$table = $session_name;<br />

return true;<br />

}<br />

Once a session has been opened, the read and write handlers are called as necessary<br />

to get the current state information and to store that state in a persistent manner.<br />

The read handler is given the session ID, and the write handler is called with the session’s<br />

ID and the data for the session. Our database read and write handlers query<br />

and update the database table:<br />

function read($session_id) {<br />

global $table;<br />

$result = mysql_query("SELECT value FROM $table<br />

WHERE session_id='$session_id'");<br />

if($result && mysql_num_rows($result)) {<br />

return mysql_result($result,0);<br />

} else {<br />

error_log("read: ".mysql_error( )."\n",3,"/tmp/errors.log");<br />

return "";<br />

}<br />

}<br />

function write($session_id, $data) {<br />

global $table;<br />

$data = addslashes($data);<br />

mysql_query("REPLACE INTO $table (session_id,value)<br />

VALUES('$session_id','$data')")<br />

or error_log("write: ".mysql_error( )."\n",3,"/tmp/errors.log");<br />

return true;<br />

}<br />

Complementing the open handler is the close handler, which is called after each<br />

page’s script is done executing. It performs any cleanup necessary when closing a<br />

session (usually very minimal). Our database close handler simply closes the database<br />

connection:<br />

function close() {<br />

mysql_close();<br />

return true;<br />

}<br />

186 | Chapter 7: Web Techniques<br />

This is the Title of the Book, eMatter Edition<br />

Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!