object- and mysql-based session-handler, requires the following table:
CREATE TABLE `ws_sessions` (
`session_id` varchar(255) binary NOT NULL default '',
`session_expires` int(10) unsigned NOT NULL default '0',
`session_data` text,
PRIMARY KEY (`session_id`)
) TYPE=InnoDB;
<?php
class session {
var $lifeTime;
var $dbHandle;
function open($savePath, $sessName) {
$this->lifeTime = get_cfg_var("session.gc_maxlifetime");
$dbHandle = @mysql_connect("server","user","password");
$dbSel = @mysql_select_db("database",$dbHandle);
if(!$dbHandle || !$dbSel)
return false;
$this->dbHandle = $dbHandle;
return true;
}
function close() {
$this->gc(ini_get('session.gc_maxlifetime'));
return @mysql_close($this->dbHandle);
}
function read($sessID) {
$res = mysql_query("SELECT session_data AS d FROM ws_sessions
WHERE session_id = '$sessID'
AND session_expires > ".time(),$this->dbHandle);
if($row = mysql_fetch_assoc($res))
return $row['d'];
return "";
}
function write($sessID,$sessData) {
$newExp = time() + $this->lifeTime;
$res = mysql_query("SELECT * FROM ws_sessions
WHERE session_id = '$sessID'",$this->dbHandle);
if(mysql_num_rows($res)) {
mysql_query("UPDATE ws_sessions
SET session_expires = '$newExp',
session_data = '$sessData'
WHERE session_id = '$sessID'",$this->dbHandle);
if(mysql_affected_rows($this->dbHandle))
return true;
}
else {
mysql_query("INSERT INTO ws_sessions (
session_id,
session_expires,
session_data)
VALUES(
'$sessID',
'$newExp',
'$sessData')",$this->dbHandle);
if(mysql_affected_rows($this->dbHandle))
return true;
}
return false;
}
function destroy($sessID) {
mysql_query("DELETE FROM ws_sessions WHERE session_id = '$sessID'",$this->dbHandle);
if(mysql_affected_rows($this->dbHandle))
return true;
return false;
}
function gc($sessMaxLifeTime) {
mysql_query("DELETE FROM ws_sessions WHERE session_expires < ".time(),$this->dbHandle);
return mysql_affected_rows($this->dbHandle);
}
}
$session = new session();
session_set_save_handler(array(&$session,"open"),
array(&$session,"close"),
array(&$session,"read"),
array(&$session,"write"),
array(&$session,"destroy"),
array(&$session,"gc"));
session_start();
?>