[code=php]
<?php
/**
 * DBsession
 * custom method to make sessions
 * this class uses sessions wich are set in a database
 * 
 * @author: Arjan Veldkamp <arjan@arjanv.nl>
 * @date: 27/06/2011
 */
class DBsession {

	/**
	 * How long a session should exist
	**/
	public $lifetime = 3600;
	
	private $_sessie;
	private $_sessiedb = 'sessies';
	private $_sessiondatadb = 'sessies_data';
	
	protected $secret;
	protected $sessiondata = array();

	public function __construct() {
		$_SESSION = array();
		$this->secret = sha1(md5('mySecreyKey'));
		$this->prepareSession();
	}	
	
	/**
	 * Check if we need to update or create a new session
	 */
	
	public function prepareSession() {
		if(!isset($_COOKIE[$this->secret])) {
			$this->_startSession();
		} else {
			$this->_extendSession();
		}
		
		$this->_getSessionData();
	}
	
	/**
	 * Start a new session, the user has not been here before, or the old session has been expired
	 * 
	 * We will put a cookie on the user's machine with a key, this key gives access to the data assigned to this cookie
	 */
	
	protected function _startSession() {
		$exptime = time() + $this->lifetime;
		$sessname = $this->_createSessionName();
		setcookie($this->secret, $sessname, $exptime);
		$sql = 'INSERT INTO '.$this->_sessiedb.'
				(naam, gestart_op, laatste_actie, expires)
				VALUES("'.$sessname.'", NOW(), NOW(), '.$exptime.')';
		if(!mysql_query($sql)) {
			setcookie($this->secret, $sessname, time() - 3600);
			throw new Exception('Er trad een fout op tijdens het maken van een sessiekey', 2);
		}
		
		$this->_sessie = $sessname;
	}
	
	/**
	 * This user has been here before within the given lifetime of the session
	 * 
	 * We are gonna extend the cookie with the given lifetime
	 */
	
	protected function _extendSession() {
		$exptime = time() + $this->lifetime;
		$this->_sessie = $_COOKIE[$this->secret];
		setcookie($this->secret, $this->_sessie, $exptime);
		$sql = 'SELECT naam
				FROM '.$this->_sessiedb.'
				WHERE naam = "'.$this->_sessie.'"
				AND expires > '.time();
		$rs = mysql_query($sql);
		if(mysql_num_rows($rs) == 1) {
			$sql = 'UPDATE '.$this->_sessiedb.'
						SET	expires = '.$exptime.',
							laatste_actie = NOW()
					WHERE naam = "'.$this->_sessie.'"';
			
			if(!mysql_query($sql)) {
				throw new Exception('Er trad een fout op tijdens het verlengen van de sessiekey', 2);
			}
		} else {
			$this->_startSession();
		}
		
	}
	
	/**
	 * Get all session-data wich fits with the sessionkey
	 * The sessionkey connects the browser with the sessiondata
	 */
	
	protected function _getSessionData() {
		$sql = 'SELECT sessnaam, sessdata
				FROM '.$this->_sessiondatadb.'
				WHERE sessid = "'.$this->_sessie.'"';
		$rs = mysql_query($sql);
		if(mysql_num_rows($rs) > 0) {
			while($row = mysql_fetch_assoc($rs)) {
				$this->sessiondata[$row['sessnaam']] = $row['sessdata'];
			}
		}
	}
	
	/**
	 * Get the session
	 */
	
	public function getSession($key) {
		if(array_key_exists($key, $this->sessiondata)) {
			return $this->sessiondata[$key];
		}
		
		return false;
	}
	
	/**
	 * Set a new session variable
	 * @param string - session-name
	 * @param mixed - the session's value
	 * 
	 * When the session-name allready exists, update it with the new value
	 */
	
	public function setSession($naam, $val='') {
		if(!array_key_exists($naam, $this->sessiondata)) {
			$sql = 'INSERT INTO '.$this->_sessiondatadb.'
						(sessid, sessnaam, sessdata)
					VALUES( "'.$this->_sessie.'", "'.$naam.'", "'.$val.'")';
			if(!mysql_query($sql)) {
				throw new Exception('Er is een fout opgetreden tijdens het maken van een sessie');
			}
		} else {
			$sql = 'UPDATE '.$this->_sessiondatadb.'
					SET sessdata = "'.$val.'"
					WHERE sessid = "'.$this->_sessie.'" AND sessnaam = "'.$naam.'"';
			if(!mysql_query($sql)) {
				throw new Exception('Er is een fout opgetreden tijdens het updaten van een sessie');
			}
		}
		
		$this->sessiondata[$naam] = $val;
		return true;
	}
	
	/**
	 * Delete a session
	 * @param string - session wich you would like to destroy
	 * @return void
	 */
	
	public function deleteSession($naam) {
		if(array_key_exists($naam, $this->sessiondata)) {
			unset($this->sessiondata[$naam]);
			$sql = 'DELETE FROM '.$this->_sessiondatadb.'
					WHERE sessid = "'.$this->_sessie.'" AND sessnaam = "'.$naam.'"';
					
			mysql_query($sql);
		}
	}
	
	/**
	 * Create a unique id
	 */
	
	protected function _createSessionName() {
		return md5(uniqid());	
	}
}
?>
