Session Handler (obs! ikke lavet af mig)

Release your script here.
State:
- Author
- What it does
- Perhaps a little guide.
- Also, if the snippet is of any use to the community, it has a chance of getting posted on the main page, so don't hesitate to submit/ask!

Session Handler (obs! ikke lavet af mig)

Postby Dandy » Mon Mar 03, 2008 8:50 pm

Her paster jeg et script som jeg har haft gemt, det er lavet er Gnu på www.udvikleren.dk og virker rigtig smart ;)

Koden her skal bare smides i en fil der hedder session.php f.eks. også skal den ellers inkluderes i undersiderne
* Handles sessions in a more fasionable way.
* @package Blob
* @class Session

Klassen herunder styrer sessions på en elegant måde via OOP.

Code: Select all
<?php
/**
 * Project:      Blob: Core engine
 * File:        session.php
 *
 * This code is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This code is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * @link http://www.blobmedia.dk/
 * @copyright 2008 Blob Media
 * @author Michael Larsen <ml at blobmedia dot dk>
 * @package Blob
 * @version 1.0
 */
 
/**
 * Handles sessions in a more fasionable way.
 * @package Blob
 * @class Session
 */
class Session
{
   /**
    * @cfg {string} $namespace Namespace for locating session data
    */
   private $namespace;
   
   /**
    * @cfg {boolean} $autoCreate Auto create session namespace if
    * it does not exist. Defaults to true.
    */      
   private $autoCreate = true;

   /**
    * @cfg {boolean} $throwErrors True to allow throwing exceptions
    * caused by class. Defaults to true.
    */      
   private $throwErrors = true;

   /**
    * Data container.
    */
   private $data = NULL;
   
   /**
    * The class constructor
    */
   function __construct(array $config = array()) {
      if(!$_SESSION) {
         @session_start();
      }
      
      // Security checks
      if (!isset($_SESSION['initiated'])) {
         session_regenerate_id();
         $_SESSION['initiated'] = true;
      }
      
      if (isset($_SESSION['HTTP_USER_AGENT'])) {
         if ($_SESSION['HTTP_USER_AGENT'] != md5($_SERVER['HTTP_USER_AGENT'])) {
            die('Invalid user access');
         }
      } else {
         $_SESSION['HTTP_USER_AGENT'] = md5($_SERVER['HTTP_USER_AGENT']);
      }
      
      if(empty($config['namespace']) && !in_array($config['namespace'],array('initiated','HTTP_USER_AGENT'))) {
         if($this->throwErrors !== true) {
            throw new SessionException('Could not create session, namespace not valid.');
         } else {
            return;
         }
      }
      
      $this->namespace = $config['namespace'];
      
      if(!$this->exists()) {
         $_SESSION[$this->namespace] = array();
      }
      
      $this->data = $_SESSION[$this->namespace];
      unset($_SESSION[$this->namespace]);
   }
   
   /**
    * The class destructor
    */      
   function __destruct() {
      if($this->data) {
         $_SESSION[$this->namespace] = $this->data;
      }
   }
   
   /**
    * MAGIC getter
    */
   function __get($name) {
      if(!$this->exists($this->autoCreate)) {
         if($this->throwErrors !== true) {
            throw new SessionException('Could not get variable, session does not exist.');
         } else {
            return NULL;
         }
      }
      
      return $this->data[$name];
   }
   
   /**
    * MAGIC setter
    */
   function __set($name,$val) {
      if(!$this->exists($this->autoCreate)) {
         if($this->throwErrors !== true) {
            throw new SessionException('Could not set variable, session does not exist.');
         } else {
            return NULL;
         }
      }
      
      $this->data[$name] = $val;
      return $val;
   }
   
   /**
    * Return true if session of namespace exists.
    * @param {boolean} $autoCreate True to automatically create session namespace if it does not exist.
    */
   function exists($autoCreate = false) {
      if($this->namespace) {
         if($autoCreate === true) {
            $_SESSION[$this->namespace] = array();
         }
         if(isset($_SESSION[$this->namespace])) {
            return true;
         }
      }
      return false;
   }

   /**
    * Loads an array of values into the session
    * @param {array} $array Array of values
    */
   function load(array $array) {
      unset($array['namespace']);
      
      foreach($array as $name => $val) {
         $this->data[$name] = $val;
      }
   }
   
   /**
    * Removes the whole session
    */
   function remove() {
      if(!$this->exists()) {
         if($this->throwErrors !== true) {
            throw new SessionException('Could not remove session, session does not exist.');
         } else {
            return false;
         }
      }
   
      $_SESSION[$this->namespace] = NULL;
      unset($_SESSION[$this->namespace]);
      
      $this->data = NULL;
      
      return true;
   }
}

/**
 * Rewrites common exception output
 * @package Blob
 * @class SessionException
 */
class SessionException extends Exception
{
   // Redefine the exception so error message isn't optional
   public function __construct($message, $code = 0) {
      // make sure everything is assigned properly
      parent::__construct($message, $code);
   }
   
   // custom string representation of object
   public function __toString() {
      return get_class($this) . ": [{$this->code}]: {$this->message}\n";
   }
}
?>


Filen indeholder en klasse kaldet Session

filen kan bruges på følgende måde

Code: Select all
<?php
   $session = new Session(array('namespace'=>'saveNamespace'));
   $session->name = 'Blob';
   
   print $session->name;
?>
Dandy
 

Return to PHP Release

Who is online

Users browsing this forum: No registered users and 2 guests

cron