Location: PHPKode > scripts > Session Handler Class > session-handler-class/session_handle.php
<?php
/********************************************
 * Class Session Handler
 * Author:  Christian Zinke 
 *  @@ Jan #09  @@ http://christianzinke.wordpress.com/
 *  This Class handles a Session including a Cronjob if you wanne
 *  You need two tables:
 *  one SESSION Table Structur:
 *   
 *  session_id(VARCHAR)  | session_time(INT)  | session_value(TEXT) | session_user(Varchar(255))
 *  
 *  
 *  
 *  AND    cron_db
 *   
 *          ID | cron_date(varchar(16)) |
 *         ------------------------------- 
 *  Value:  1  | 000000000              |
 *  
 *  You need to insert 1 row with ID 1
 *    
 *  And you have to set a few things ;)  
 *  If you set your DB befor just do host/user/pass/database as private
 *  and set the names... 
 *
 *
 * This LICENSE is in the BSD license style.
 *
 *  for germans:
 *  http://de.wikipedia.org/wiki/BSD-Lizenz
 *    
 * Copyright (c) 2008-2009, Christian Zinke
 * http://christianzinke.wordpress.com/  
 * All rights reserved.
 *   
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   Redistributions of source code must retain the above copyright
 *   notice, this list of conditions and the following disclaimer.
 *
 *   Redistributions in binary form must reproduce the above copyright
 *   notice, this list of conditions and the following disclaimer in the
 *   documentation and/or other materials provided with the distribution.
 *
 *   Neither the name of Christian Zinke nor the names of his contributors
 *   may be used to endorse or promote products derived from this software
 *   without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *********************************************/   
class session_handler
{
  private $lifeTime;
  private $probility;
  private $gc_divisor;
  private $session_path;
  public $session_table='session_table';
  private $mySQL_ID;
  public $hostname="localhost";
  public $user='root'; 
  public $pass='';
  public $database='myproject';
  public $cron_php='cron.php';
  public $cron_db='cron_db';
  public $activate_cron=false;
  public $save_in_db=false;
  public $regenerate_id=false;
  private $attack=false;
  
  public function __construct ($l=false,$p=false,$g=false,$s=false) 
  {
    // Configurations - most Servers apply
    ini_set('allow_url_fopen', 0);
    ini_set('allow_url_include', 0);
    ini_set('magic_quotes_gpc', 0);
    ini_set('magic_quotes_runtime', 0);
    
    if($l===false)
      $this->lifeTime = get_cfg_var("session.gc_maxlifetime");
    else
      $this->lifeTime=$l;
    if($p===false)
      $this->probility = get_cfg_var("session.gc_probability");
    else
      $this->probility=$p;
    if($g===false)
      $this->gc_divisor = get_cfg_var("session.gc_divisor");
    else
      $this->gc_divisor=$g;
    if($s===false)
      $this->session_path= 'tmp\\';
    else
      $this->session_path=$s;
    //importent
    ini_set('session.use_cookies'     ,1); 
    ini_set('session.use_only_cookies',1); 
    ini_set('session.use_trans_sid'   ,0); 
    //rest of INIset
  }
  
  private function connect()
  {
    
      $this->mySQL_ID = mysql_connect($this->host_name,$this->user,$this->pass);
      if (!$this->mySQL_ID) 
      {
        die ('Connecting Error!');
      }
      else
      {
      }
	    $db_selected = mysql_select_db($this->database, $this->mySQL_ID);
	    if (!$db_selected) 
      {
        die ('Connecting Error!');
      }
      else
      {
      }  
  }
  
  private function cron()
  {
    $this->connect();
    $today = mktime(0,0,0,date("m"),date("d"),date("y"));
    $sql=sprintf("SELECT cron_date FROM %s WHERE ID = '1'",
    $this->cron_db);
    $result = mysql_query($sql);
    $last = mysql_fetch_row($result);
    //Yesterday
    if ($last[0] < $today) 
    {
    //make your Jobs 
      require_once($this->cron_php);
    //Update SQL Table
      $sql_u = sprintf("UPDATE %s SET cron_date = '%s' WHERE ID = '1'",
      $this->cron_db,
      $today
      );
      mysql_query($sql_u);
    }  
  }
  
  public function oeffne($speicherpfad, $session_name)
  {
    if($this->save_in_db === true)
    {
      $this->connect();
    }
    return true; 
  }

  public function schliesse()
  {
      mysql_close($this->mySQL_ID);
      return true;
  }

  public function lese($id)
  {
    if($this->save_in_db === true)
    {
      $user_unique=md5($_SERVER['HTTP_USER_AGENT'].$_SERVER['HTTP_USER_AGENT'].$_SERVER['REMOTE_HOST']); 
      $sql = sprintf("SELECT session_value FROM %s WHERE session_id = '%s' AND  session_user = '%s'",
           $this->session_table,
           mysql_real_escape_string(trim($id)),
           $user_unique);
      $result = mysql_query($sql);
      //Errorhandling
      
      if (!$result)
        return '';
      if (!mysql_num_rows($result))
        return '';
    // Output Data
      $row = mysql_fetch_row($result);
        return $row[0];
    }
  }
  
  private function check_user_unique()
  {
  
  }
  
  private function get_sess_id()
  {
  
      $sql = sprintf("SELECT session_id,session_user FROM %s WHERE session_user = '%s'
      AND session_id='%s'",
      $this->session_table,
      $_SESSION['user_unique'],
      session_id());      
      $result = mysql_query($sql);
      $row = mysql_fetch_row($result);
  
      if(isset($row))
        return $row;
  }

  public function schreibe($id, $sess_daten)
  {
  //Check old Entrys...
  // Unique - 'HTTP_USER_AGENT' -  'REMOTE_ADDR'  - 'REMOTE_HOST'
  //  ->  md5($_SERVER['HTTP_USER_AGENT'].$_SERVER['HTTP_USER_AGENT'].$_SERVER['REMOTE_HOST']);<br />
    if($this->save_in_db === true)
    { 
      
      $this->gc($this->lifeTime);
      $row=$this->get_sess_id();
      $user_unique=md5($_SERVER['HTTP_USER_AGENT'].$_SERVER['HTTP_USER_AGENT'].$_SERVER['REMOTE_HOST']);
      
      if(isset($row[0]))
      {
          $sql = sprintf("UPDATE %s SET session_time = '%s', 
                          session_value='%s'
                          WHERE session_user = '%s'",
           $this->session_table,
           time(),
           mysql_real_escape_string(trim($sess_daten)),
           mysql_real_escape_string(trim($_SESSION['user_unique'])));
      }
      else
      {
        if($user_unique==$_SESSION['user_unique'])
        {
           $sql = sprintf("INSERT INTO %s (session_id,session_time,session_value, session_user)
           VALUES ('%s','%s','%s','%s')",
           $this->session_table,
           mysql_real_escape_string(trim($id)),
           time(),
           mysql_real_escape_string(trim($sess_daten)),
           $user_unique);
        
        }
        else
        {
            $sess_daten='';
            return false;
        }
      }
      $result=mysql_query($sql);
      return $result;
    } 
  }

  public function loesche($id)
  {
    if($this->save_in_db === true)
    { 
      $sql = sprintf("DELETE FROM %s WHERE session_id = '%s'",
           $this->session_table,
           mysql_real_escape_string($id));
      $result=mysql_query($sql);
      return $result;
    } 
  }

  public function gc($maxlifetime)
  {
    if($this->save_in_db === true)
    {
      $ses_life = time()-$maxlifetime;
      $sql = sprintf("DELETE FROM %s WHERE session_time < '%s'",
           $this->session_table,
           $ses_life);            
      $result=mysql_query($sql);
      return $result;
    } 
  }
  
  public function execute()
  {
    session_save_path($this->session_path);
    ini_set('session.gc_maxlifetime', $this->lifeTime);
    ini_set('session.gc_probability', $this->probility);
    ini_set('session.gc_divisor', $this->gc_divisor);
    session_set_save_handler(
    array($this,"oeffne"), 
    array($this,"schliesse"), 
    array($this,"lese"), 
    array($this,"schreibe"), 
    array($this,"loesche"), 
    array($this,"gc"));
    if($this->activate_cron===true)
    {
      $this->cron();
    }
    session_start();
    $_SESSION['user_unique']=md5($_SERVER['HTTP_USER_AGENT'].$_SERVER['HTTP_USER_AGENT'].$_SERVER['REMOTE_HOST']);   
    if($this->regenerate_id===true)
    { 
      session_regenerate_id(TRUE);
    }
  }
  
  
}
?>
Return current item: Session Handler Class