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.

When a session is completed, the destroy handler is called. It is responsible for cleaning<br />

up anything created during the open handler’s call. In the case of the database<br />

storage system, we must remove that session’s entry in the table:<br />

function destroy($session_id) {<br />

global $table;<br />

mysql_query( "DELETE FROM $table WHERE session_id = '$session_id'";<br />

return true;<br />

}<br />

The final handler, the garbage-collection handler, is called at intervals to clean up<br />

expired session data. The function should check for data that has not been used in<br />

longer than the lifetime given by the call to the handler. Our database garbagecollection<br />

handler removes entries from the table whose last-modified timestamp<br />

exceeds the maximum time:<br />

function gc($max_time) {<br />

global $table;<br />

mysql_query(<br />

"DELETE FROM $table WHERE UNIX_TIMESTAMP(expiration)<br />

< UNIX_TIMESTAMP()-$max_time")<br />

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

return true;<br />

}<br />

After creating all the handler functions, install them by calling session_set_save_<br />

handler() with the appropriate function names. With the preceding examples, call:<br />

session_set_save_handler('open', 'close', 'read', 'write', 'destroy', 'gc');<br />

You must call session_set_save_handler() before starting a session with session_<br />

start(). This is normally accomplished by putting the store functions and call to<br />

session_set_save_handler() in a file that’s included in every page that needs the custom<br />

session handler. For example:<br />

<br />

Because the handlers are called after output for the script is sent, no function that<br />

generates output can be called. If errors occur, log them into a file using error_log(),<br />

as we did earlier.<br />

Combining Cookies and Sessions<br />

Using a combination of cookies and your own session handler, you can preserve<br />

state across visits. Any state that should be forgotten when a user leaves the site,<br />

such as which page the user is on, can be left up to <strong>PHP</strong>’s built-in sessions. Any state<br />

that should persist between user visits, such as a unique user ID, can be stored in a<br />

cookie. With the user’s ID, you can retrieve the user’s more permanent state, such as<br />

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

Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.<br />

Maintaining State | 187

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

Saved successfully!

Ooh no, something went wrong!