Published in: PHP
PHP DB Session Class
<?php /** * @desc Session tracking class - overrides PHP session handling * @date 14/11/05 * @ver 3.2 * * @req DB tables: session {session_id[varchar32], timestamp[int11], data[text]} * * @sql CREATE TABLE `sessions` ( * `sid` varchar(32) NOT NULL default '', * `timestamp` int(11) NOT NULL default '0', * `data` text NOT NULL, * PRIMARY KEY (`sid`) * ) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE latin1_general_cs; */ class Session { var $_db; function Session() { } function _open($path, $name) { $this->_db = &Registry::GetDBConnection(); return true; } function _close() { $this->_gc(0); return true; } function _read($sid) { $sql = "SELECT data FROM sessions WHERE sid = '$sid' GROUP BY sid"; $res = $this->_db->query($sql); if(Pear::IsError($res)) { return ''; } if($row = $res->fetchRow()) { return $row['data']; }else{ return ''; } } /** * @desc create session or update it */ function _write($sid, $data) { $sql = "INSERT INTO sessions (sid, timestamp, data) VALUES ('$sid', $timestamp, '$data') "; $sql .= "ON DUPLICATE KEY UPDATE timestamp = $timestamp, data = '$data'"; $res = $this->_db->query($sql); if(Pear::IsError($res)) { return false; }else{ return true; } } function _destroy($sid) { $sql = "DELETE FROM sessions WHERE sid = '$sid'"; $res = $this->_db->query($sql); if(Pear::IsError($res)) { return false; }else{ return true; } } function _gc($life) { $sql = "DELETE FROM sessions WHERE timestamp < $timeout"; $res = $this->_db->query($sql); if(Pear::IsError($res)) { return false; }else{ return true; } } /** * @desc checks whos online now * works for separate clients and pages * * @return array of results */ function check($page_id=0) { //load current client_id for WHERE $client_id = $_SESSION['client_id']; $like_clause = '%client\_id|s:%:"' . $client_id . '"'; $like_clause .= ($page_id==0) ? "" : '%page\_id|s:%:"' . $page_id . '"'; $like_clause .= '%'; $sql = "SELECT sid, data FROM sessions "; $sql .= "WHERE data LIKE "; $sql .= " '" . $like_clause . "' "; $sql .= " GROUP BY sid"; $rows = $this->_db->query($sql); if(Pear::IsError($res)) { return false; }else{ //do session_decode to parse out values while($row = $rows->fetchRow()) { $sessions[] = $this->_unserialize($row['data']); } return $sessions; } } /* * * user_id|s:2:"19";client_id|s:1:"2"; */ function _unserialize($session) { for($i=0; $i<count($items)-1; $i++) { $result[$array[0]] = $value; } return $result; } } ?>
You need to login to post a comment.
