1 Replies - 1809 Views - Last Post: 10 September 2010 - 04:19 AM

#1 Dormilich   User is offline

  • 痛覚残留
  • member icon

Reputation: 4208
  • View blog
  • Posts: 13,283
  • Joined: 08-June 10

Session handling made easy

Posted 25 June 2010 - 03:31 AM

Description: Requires PHP 5. As usual, you must not set any session data after you started your output, otherwise you’ll get a "header already sent" warning.

you can create a session object anywhere and as often as you want in your scripts, the class will always use the same session.

// creating a 20 min session object
$s = new Session(20);

// setting a variable
$s->user = "Dormilich";

// getting a variable
if ($s->logged_in) {
doMemberStuff();
}

// getting a variable with error handling
try {
echo "Welcome back, ", $s->getVar("user"), ".";
// …
}
catch ($e) {
header("Location: login.php");
exit();
}

// force quit a session (including removal of all session data)
$s->kill();handle a session through a session object. it esp. eases the setting and reading of session variables. this comes in handy if you need to test, whether variables have been already set. incorporates the use of Exceptions.
<?php

##########################
# session handling class #
##########################

/**
 * starting and ending of sessions. if a session already exists,
 * it is continued.
 *
 * @author: Bertold von Dormilich
 * @email: [email protected]
 * @created: June 2009
 * @updated: April 2010
 */
class Session
{
	/**
	 * @var (string) $ID            session ID
	 * @var (int) $uoc              session via cookie
	 * @var (bool) $clt             use URL for ID submit
	 * @var (bool) $cho             cookie script access
	 */
	protected static $ID  = NULL;
	public    static $clt = 0; // cookie persistence time
	public    static $uoc = true; // SID only in cookie
	public    static $cho = true; // cookie not available for client scripts
	
	/**
	 * set php.ini values (cookie-only-session, etc.) and
	 * begin/continue the session.
	 * 
	 * @param (int) $lifetime      session cache lifetime (min)
	 * @return (void)
	 */
	public function __construct(
		$lifetime = 30
	)
	{
		if (self::$ID === NULL)
		{
			ini_set('session.gc_maxlifetime',   $lifetime*60);
			ini_set('session.use_only_cookies', self::$uoc);
			ini_set('session.cookie_lifetime',  self::$clt);
			ini_set('session.cookie_httponly',  self::$cho);
			session_start();
			self::$ID = session_id();
		}
	}
	
	/**
	 * Dummy for getValue().
	 * 
	 * @param (string) $name        name of the session variable
	 * @return (mixed)              value of session variable
	 */
	public function __get(
		$key
	)
	{
		return $this->getValue($key);
	}
	
	/**
	 * Dummy for setValue().
	 * 
	 * @param (string)              name of session variable
	 * @param (mixed)               new value
	 * @return (bool)               value overwritten?
	 */
	public function __set(
		$key,
		$value
	)
	{
		return $this->setValue($key, $value);
	}
	
	/**
	 * test a session variable for existance.
	 * 
	 * @param (string)              name of session variable
	 * @return (bool)               key already registered?
	 */
	public function __isset(
		$key
	)
	{
		return isset($_SESSION[$key]);
	}
	
	/**
	 * begin or continue a session
	 * 
	 * @return (string)             current session id
	 */
	public function begin()
	{
		if (self::$ID === NULL)
		{
			session_start();
			self::$ID = session_id();
		}
		return self::$ID;
	}
	
	/**
	 * end session but don’t delete session vars/cookies.
	 * 
	 * @return (void)
	 */
	public function end()
	{
		session_destroy();
		self::$ID = NULL;
	}

	/**
	 * close session. unset session vars and class’ id, name.
	 * 
	 * @return (void)
	 */
	public function kill()
	{
		setcookie(session_name(), '', $_SERVER['REQUEST_TIME']-3600, '/');
		$_SESSION = array();
		$this->end();
	}
	
	/**
	 * make a new session id.
	 * 
	 * @param (bool) $del_data     delete or keep previous session data
	 * @return (bool)              execution success
	 */
	public function reset(
		$del_data = false
	)
	{
		$ok = session_regenerate_id((bool) $del_data);
		self::$ID = session_id();
		return $ok;
	}
	
	/**
	 * get the session id.
	 * 
	 * @return (string)             session id
	 */
	public function getSID()
	{
		return self::$ID;
	}
	
	/**
	 * get a session variable. return NULL if not existing.
	 * 
	 * @param (string) $name        name of the session variable
	 * @return (mixed)              value of session variable or NULL
	 */
	public function getValue(
		$name
	)
	{
		if (!isset($_SESSION[$name]))
		{
			return NULL;
		}
		return $_SESSION[$name];
	}
	
	/**
	 * get session variable. throw exception if not existing.
	 * 
	 * @param (string) $name        name of the session variable
	 * @return (mixed)              value of session variable
	 * @throws (Exception)          session variable not set
	 */
	public function getVar(
		$name
	)
	{
		if (!isset($_SESSION[$name]))
		{
			$emsg = "Session variable '$name' doesn’t exist.";
			throw new Exception($emsg);
		}
		return $_SESSION[$name];
	}
	
	/**
	 * set a new session variable’s value, regardless if the variable
	 * already exists or not.
	 * 
	 * @param (string)              name of session variable
	 * @param (mixed)               new value
	 * @return (bool)               value overwritten?
	 */
	public function setValue(
		$name, 
		$wert
	)
	{
		$old = isset($_SESSION[$name]);
		$_SESSION[$name] = $wert;
		return $old;
	}
}
?>



Is This A Good Question/Topic? 0
  • +

Replies To: Session handling made easy

#2 huzi8t9   User is offline

  • D.I.C Regular
  • member icon

Reputation: 25
  • View blog
  • Posts: 369
  • Joined: 11-July 07

Re: Session handling made easy

Posted 10 September 2010 - 04:19 AM

Nice class, thanks for sharing (:
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1