note 58071 deleted from function.session-set-save-handler by danbrown
| From: | danbrown@php.net | Date: | Sun, 23 Jan 2011 16:18:08 +0000 |
| Subject: | note 58071 deleted from function.session-set-save-handler by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-176043@lists.php.net to get a copy of this message | ||
Note Submitter: Keamos at gmail dot com
----
Here's a set of session-handling functions that uses PEAR::DB and a database to store the php
sessions. The only assumption I make is your PEAR::DB object is called $db.
mySQL:
CREATE TABLE
sessions (
sessionid varchar(40) binary NOT NULL default '',
expiry int(10) unsigned NOT NULL default '0',
value text NOT NULL,
PRIMARY KEY (sessionid)
) TYPE=MyISAM COMMENT='Sessions';
<?
$sessionLifetime = get_cfg_var("session.gc_maxlifetime");
function _openSession($savePath, $id)
{
//We don't need to create any new file handles, et cetera
return TRUE;
}
function _closeSession()
{
//We don't need to close any file handles, et cetera
return TRUE;
}
function _readSession($sessionid)
{
global $db, $sessionLifetime;
$sessionid = $db->quoteSmart($sessionid);
$time = time();
$sql = 'SELECT value FROM ' . SESSIONS_TABLE . " WHERE
sessionid=$sessionid AND expiry > $time";
$result = $db->getOne($sql);
if (PEAR::isError($result))
{
//Must return "" because php.net says so
return "";
}
else
{
return $result;
}
//Something slipped through the cracks, so throw an error
return "";
}
function _writeSession($sessionid, $sessionData)
{
global $db, $sessionLifetime;
$expiry = time() + $sessionLifetime;
$sessionid = $db->quoteSmart($sessionid);
$sessionData = $db->quoteSmart($sessionData);
$sql = 'SELECT expiry FROM ' . SESSIONS_TABLE . " WHERE
sessionid=$sessionid";
$result = $db->getOne($sql);
if ($result === NULL)
{
$sql = 'INSERT INTO ' . SESSIONS_TABLE . " (sessionid,
expiry, value) VALUES ($sessionid, $expiry, $sessionData)";
$result = $db->query($sql);
if (PEAR::isError($result))
{
//error of some sort
return FALSE;
}
return TRUE;
}
else
{
$sql = 'UPDATE ' . SESSIONS_TABLE . " SET
expiry=$expiry, value=$sessionData WHERE
sessionid=$sessionid";
$result = $db->query($sql);
//Something went wrong
if (PEAR::isError($result))
{
return FALSE;
}
return TRUE;
}
//Something slipped through, so throw an error
return FALSE;
}
function _destroySession($sessionid)
{
global $db;
$sessionid = $db->quoteSmart($sessionid);
$sql = 'DELETE FROM ' . SESSIONS_TABLE . " WHERE
sessionid=$sessionid";
$result = $db->query($sql);
if (!PEAR::isError($result))
{
return TRUE;
}
return FALSE;
}
function _gcSession($maxlifetime)
{
global $db;
$time = $db->quoteSmart(time());
$sql = 'DELETE FROM ' . SESSIONS_TABLE . " WHERE expiry < $time";
$result = $db->query($sql);
if (PEAR::isError($result))
{
return 0;
}
return $db->affectedRows();
}
session_set_save_handler("_openSession", "_closeSession",
"_readSession", "_writeSession", "_destroySession",
"_gcSession");
?>