Jump to content

Help with database session class not retaining session data


CroNiX

Recommended Posts

I have been tinkering around with this class and just can't get it to work.  Everything works like its supposed to EXCEPT it does not retain the session data when going from one page to the next.  When I add a session variable ($_SESSION['foo']='bar') I can see it getting inserted into the database and can see it when doing a var_dump($_SESSION), but when I go to another page the data is wiped out of both.

 

I had been reading if you use php5 (which I am) you need to use register_shutdown_function('session_write_close'); to preserve the data because PHP5 destroys the object and doesn't properly close the session if using it in a class.  I have used register_shutdown_function('session_write_close'); in both the __construct() and __destruct() methods, but it doesn't seem to help.

 

If I need to post the database class I will, although I don't think the problem is there as I use it a lot.

Yes, I instantiate the database class and the session class at the top of every page.

$db = new MySQLiDB(HOST, USER, PASS, DBNAME);

$session = new SessionManager($db);

 

Any help would be greatly appreciated.  Ive been banging my head for too long over this and I am pretty much a OOP noob, so Im drawing a blank.

Thanks!

 

<?php
/*
CREATE TABLE `sessions` (
  `session_id` varchar(100) NOT NULL default '',
  `session_data` text NOT NULL,
  `expires` int(11) NOT NULL default '0',
  PRIMARY KEY  (`session_id`)
) TYPE=MyISAM;
*/
class SessionManager {

   	private $life_time;
private $db;
public $sessid;

   	function __construct($db_object) {
      // Read the maxlifetime setting from PHP
      	$this->life_time = get_cfg_var("session.gc_maxlifetime");
      	$this->db = $db_object;
      	// Register this object as the session handler
	session_set_save_handler( 
        	array( $this, "open" ), 
        	array( $this, "close" ),
        	array( $this, "read" ),
        	array( $this, "write"),
        	array( $this, "destroy"),
        	array( $this, "gc" )
      	);
      	register_shutdown_function('session_write_close');
	session_start();
}

function open( $save_path, $session_name ) {
      	global $sess_save_path;
	$sess_save_path = $save_path;
      	// Don't need to do anything. Just return TRUE.
      	return true;
   	}

   	function close() {
      	return true;
   	}

   	function read( $id ) {
      	
   		// Set empty result
      	$data = array();
      	// Fetch session data from the selected database

      	$time = time();
      	$newid = $this->db->escape($id);
      	$this->sessid = $newid;
      	
      	$sql = "SELECT `session_data` FROM `sessions` WHERE `session_id` = '$newid' AND `expires` > $time";
      	$rs = $this->db->query($sql);                           
      	
      	if($this->db->numRows($rs) > 0) {
        	$data = $this->db->fetchAssoc($this->db->rs);
        	$this->db->closeRS();
      	}       
      	return $data;
   	}

   	function write( $id, $data ) {
      	// Build query                
      	$time = time() + $this->life_time;
      	$newid = $this->db->escape($id);
      	$this->sessid = $newid;
      	$newdata = $this->db->escape($data);
      	$sql = "REPLACE `sessions` (`session_id`,`session_data`,`expires`) VALUES('$newid', '$newdata', $time)";
      	$this->db->query($sql);
      	return TRUE;
   	}

   	function destroy( $id ) {
      	// Build query
      	$newid = $this->db->escape($id);
      	$q = "DELETE FROM `sessions` WHERE `session_id` = '$newid'";
      	$this->db->query($q);
      	return TRUE;
   	}

   	function gc() {
      	// Garbage Collection
      	// Build DELETE query.  Delete all records who have passed the expiration time
      	$sql = 'DELETE FROM `sessions` WHERE `expires` < UNIX_TIMESTAMP();';
      	$this->db->query($sql);
      	// Always return TRUE
      	return true;
   	}
   	function getSessid(){
   		return $this->sessid;
   	}
   	public function __destruct(){
        session_write_close();
    }
   	
}
?>

Link to comment
Share on other sites

Get your application code working with the built-in session file handling (which is about 100 times faster than a custom handler using slow parsed/tokenized/interpreted php code), then if you have a need to use custom session handling, add that. About the only time that a custom session handler is needed is when you have a need to share session data between multiple servers. All other normal issues can be solved using the built in file handling functions.

 

Since you can see the data being inserted, it is likely that the custom session handling is working and it is more likely that you application code is overwriting the $_SESSION variables, which then overwrite the data in the database.

 

You would need to post your application code that is setting/using the $_SESSION variables to get any specific help with what it might be doing.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.