session_set_save_hanlder
Posted: Fri Aug 29, 2008 10:35 am
Hi,
I've done a code with session_set_save_handler, for handling sessions through database. I implemented all the methods in a session class
Here is the code
Unfortunately, when I do session_start() and set an parameter $_SESSION['info'] and access it through read method in the same page, I'm not able to retrieve the value. It works only when I refresh. Can somebody explain, where am I doing mistake here. I'm sorry, I've to edit some variables..
I've done a code with session_set_save_handler, for handling sessions through database. I implemented all the methods in a session class
Here is the code
Code: Select all
Class Session{
public $lifetime;
protected $db;
public $data = array();
public function open($savePath,$sessionName){
$this->lifetime = get_cfg_var("session.gc_maxlifetime");
$this->db = new DB();
if(!$this->db){
return false;
}
$this->data = $this->read(session_id());
return true;
}
public function close(){
return true;
}
public function read($sessionID){
global $our_var;
$user_id = $our_var['user_id'];
$sql = "SELECT session_data from sessions where session_key ='$sessionID' and user_id = '$user_id' ";
$res = $this->db->executeSelectArray($sql);
if(count($res) != 0){
return $res[0];
}
return null;
}
public function write($sessionID,$sessionData){
$newExp = time() + $this->lifetime;
global $our_var;
$user_id = $our_var['user_id'];
$sql = "SELECT session_data from sessions where session_key ='$sessionID' and user_id = '$user_id' ";
$res = $this->db->executeSelect($sql);
if(count($res)>0){
$update_query = "UPDATE sessions SET modify_date=NOW(),session_expires='".$newExp."',session_data='".serialize($sessionData)."' WHERE session_key='".$sessionID."' and user_id='".$user_id."' ";
$count = $this->db->executeQuery($update_query);
if($count >0 ){
return $this->read($sessionID);
}
}else{
$insert = "INSERT into sessions(user_id,session_key,session_data,begin_time,session_expires,create_date,modify_date) VALUES('$user_id','$sessionID','".serialize($sessionData)."',NOW(),'$this->lifetime',NOW(),NOW())";
$count = $this->db->executeQuery($insert);
if($count >0 ){
return $this->read($sessionID);
}
return false;
}
}
public function destroy($sessionID){
$query = "DELETE FROM sessions where session_key='$sessionID'";
$rows = $this->db->executeQuery($query);
if($rows >0){
$this->data = array();
return true;
}
return false;
}
public function gc($sessionMaxLifeTime){
$query = "DELETE FROM sessions where session_expires< '".time()."'";
$rows = $this->db->executeQuery($query);
return $rows;
}
}