/    Sign up×
Community /Pin to ProfileBookmark

Updates OOP session handler, comments please.

Well i wrote this a while ago and people told me to do this and that so i made a new one

session.php

[code=php]
<?php
class sessionHandler
{
protected static $_debug = 0;
protected static $_session = array();
protected static $getSessionByUid;
protected static $getSessionByIds;
protected static $updateSessionLastUse;
protected static $updateSession;
protected static $writeSession;
protected static $deleteSession;
protected static $deleteOldSession;

public static function init(&$db,$settings = array() )
{
// get session life time
self::$_session[‘lifetime’] = in_array(‘lifetime’ ,$settings) ? $settings[‘lifetime’] : get_cfg_var(“session.gc_maxlifetime”);
self::$_debug = $settings[‘debug’];

self::$getSessionByUid = $db->prepare(‘SELECT * FROM [sessions] WHERE `uid` = :UID’);
self::$getSessionByIds = $db->prepare(‘SELECT * FROM [sessions] WHERE `uid` = :UID AND `SID` = :SID’);

self::$updateSessionLastUse = $db->prepare(‘UPDATE [sessions] SET `time` = :time WHERE `sid` = :SID AND `UID` = :UID’);
self::$updateSession = $db->prepare(‘UPDATE [sessions] SET `value` = :value, `time`= :time WHERE `SID` = :SID AND `UID` = :UID’);

self::$writeSession = $db->prepare(‘INSERT INTO [sessions] (UID,SID,value,ip,time) VALUES (:UID,:SID,:value,:ip,:time)’);

self::$deleteSession = $db->prepare(‘DELETE FROM [sessions] WHERE UID = ? AND SID = ?’);
self::$deleteOldSession = $db->prepare(‘DELETE FROM [sessions] WHERE time < ?’);

self::garbage();

}

final private static function generate_uid()
{
while(empty(self::$_session[‘UID’]))
{
$UID = substr( md5( uniqid( rand(), true) ), 1, 18);
self::$getSessionByUid->execute(array(‘:UID’ => $UID));
$exists = self::$getSessionByUid->fetchAll();

if(empty($exists))
{
self::$_session[‘UID’] = $UID;
return $UID;
}
}
}

public function set_uid($UID)
{
if(empty($UID))
{
return self::generate_uid();
}

self::$getSessionByUid->execute(array(‘:UID’ => $UID));
$uid = self::$getSessionByUid->fetchAll();
if($uid[0][‘ip’] != $_SERVER[‘REMOTE_ADDR’])
{
return self::generate_uid();
}

return self::$_session[‘UID’] = $UID;
}

protected static function read($sid)
{
self::$getSessionByIds->execute(array(‘:SID’ => $sid, ‘:UID’ => self::$_session[‘UID’]));
$row = self::$getSessionByIds->fetchAll();
if(!empty($row))
{
self::$updateSessionLastUse->execute(array(‘:time’ => time() + self::$_session[‘lifetime’],’:SID’ => $sid, ‘:UID’ => self::$_session[‘UID’]));
}

return empty($row[0][‘value’]) ? 0 : unserialize($row[0][‘value’]);
}

protected static function write($sid, $value)
{
if($this->_debug)
{
echo ‘write@sessionHandler (‘.$sid.’:’.print_r($value).’)’;
}

self::$getSessionByIds->execute(array(self::$_session[‘UID’], $sid));
$exists = self::$getSessionByIds->fetchAll();
if(!empty($exists))
{

self::$updateSession->execute(array(‘:value’ => $value,’:time’ => time() +self::$_session[‘lifetime’],’:SID’ => $sid,’:UID’ => self::$_session[‘UID’]));
}
else
{
self::$writeSession->execute(array(‘:UID’ => self::$_session[‘UID’], ‘:SID’ => $sid, ‘:value’ => $value, ‘:ip’ => $_SERVER[‘REMOTE_ADDR’],’:time’ => time() + self::$_session[‘lifetime’]));
}
}

protected static function delete($sid)
{
self::$deleteSession->execute(array(self::$_session[‘UID’], $sid));
}

final private static function garbage()
{

self::$deleteOldSession->execute(array(time()));
}
}

final class session extends sessionHandler
{
public function __construct(&$db,$config)
{
parent::init($db,$config);
}

public function unRegister()
{
$names = func_get_args();
foreach($names as $name)
{
parent::delete($name);
}
}

public function __get($sid)
{
return parent::read($sid);
}

public function __set($sid,$value)
{
return parent::write($sid, serialize($value));
}
}
?>
[/code]

how do use it

[code=php]
<?
function __autoload($class)
{
require_once(‘./cls’.DIRECTORY_SEPARATOR.strtolower($class).’.php’);
}
// connection to PDO with extended SQL class.
$db = new SQL($GLOBALS[‘config’][‘db’][‘host’],
$GLOBALS[‘config’][‘db’][‘user’],
$GLOBALS[‘config’][‘db’][‘pswd’],
$GLOBALS[‘config’][‘db’][‘db’],
$GLOBALS[‘config’][‘db’][‘system_prefix’],
$GLOBALS[‘config’][‘debug’]
);
$session = new session($db,array(‘lifetime’ => 10 * 60,’debug’ => $GLOBALS[‘config’][‘debug’]));
$cookie = new cookie();

$cookie->session_uid = $session->set_uid($cookie->session_uid);

$session->test = array(‘foo’ => ‘bar’);

print_r($session->test);
?>
[/code]

result

[code]
array(
‘foo’ => ‘bar’
)
[/code]

Please leave comment on how to make it better.

to post a comment
PHP

4 Comments(s)

Copy linkTweet thisAlerts:
@kattenauthorJan 22.2007 — views but no comments :/
Copy linkTweet thisAlerts:
@NogDogJan 22.2007 — If I wanted to save session data in a database, I'd probably do something along the lines of the example by "stalker at ruun dot de" on the [url=http://www.php.net/session_set_save_handler]session_set_save_handler page[/url], letting the built-in PHP session functionality handle the cookie issues and just deal with the database interface, passing the applicable methods to the session_set_save_handler() function.
Copy linkTweet thisAlerts:
@kattenauthorJan 22.2007 — If I wanted to save session data in a database, I'd probably do something along the lines of the example by "stalker at ruun dot de" on the [url=http://www.php.net/session_set_save_handler]session_set_save_handler page[/url], letting the built-in PHP session functionality handle the cookie issues and just deal with the database interface, passing the applicable methods to the session_set_save_handler() function.[/QUOTE] Possible for you to explain in abit easier english i'm only 15.
Copy linkTweet thisAlerts:
@NogDogJan 22.2007 — Start by reading the [url=http://www.php.net/session_set_save_handler]session_set_save_handler[/url] documentation. It allows you to specify your own set of functions to be used for reading/writing session data instead of the default PHP system functions that do so. So if your class contained methods for each of the six required functions that must be passed to the session_set_save_handler() function. Your class file might then be something like:
[code=php]
<?php
class sessionHandler {
// your class definition, which would include the following methods:
// "open", "close","read","write","destroy", and "gc"
}

// instantiate and apply it:
$session = new sessionHandler();
session_set_save_handler(array(&$session,"open"),
array(&$session,"close"),
array(&$session,"read"),
array(&$session,"write"),
array(&$session,"destroy"),
array(&$session,"gc"));
session_start();
?>
[/code]

Then any session-controlled page would just need to do...[code=php]require 'sessionHandler.php';[/code]...to start session processing. After that it could read/write values from/to the $_SESSION array just as with "normal" sessions.
×

Success!

Help @katten spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.8,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...