Ver Mensaje Individual
  #3 (permalink)  
Antiguo 15/02/2010, 06:49
Nisrokh
 
Fecha de Ingreso: septiembre-2009
Ubicación: Neuquén
Mensajes: 142
Antigüedad: 14 años, 6 meses
Puntos: 12
Respuesta: [APORTE] Sistema de Sesiones y Autentificación de usuario con MySQL

Continuacion de SimpleSession.php
Código PHP:
Ver original
  1. <?php
  2.  
  3. /**
  4.  * Simple Session
  5.  *
  6.  * @package SimpleSession
  7.  * @author Diego P. M. Baltar <[email protected]>
  8.  * @copyright 2010
  9.  * @version 0.2
  10.  */
  11. class SimpleSession extends SimpleLogin {
  12.    
  13.     /**
  14.      * Session garbage collector divisor
  15.      *
  16.      * @access private
  17.      * @var integer
  18.      */
  19.     private $gc_divisor = 100;
  20.    
  21.     /**
  22.      * Session garbage collector lifetime
  23.      *
  24.      * @access private
  25.      * @var integer
  26.      */
  27.     private $gc_maxlifetime = 3600;
  28.    
  29.     /**
  30.      * Session garbage collector probability
  31.      *
  32.      * @access private
  33.      * @var integer
  34.      */
  35.     private $gc_probability = 10;
  36.    
  37.     /**
  38.      * Encryption available
  39.      *
  40.      * @access private
  41.      * @var boolean
  42.      */
  43.     private $encryption;
  44.    
  45.     /**
  46.      * Encryption key
  47.      *
  48.      * @access private
  49.      * @var string
  50.      */
  51.     private $encryption_key;
  52.    
  53.     /**
  54.      * SimpleMySQL object
  55.      *
  56.      * @access protected
  57.      * @var object
  58.      */
  59.     protected $mysql = null;
  60.    
  61.     /**
  62.      * Session name
  63.      *
  64.      * @access protected
  65.      * @var string
  66.      */
  67.     protected $name = '__SESSID';
  68.    
  69.     /**
  70.      * Session lifetime
  71.      *
  72.      * @access protected
  73.      * @var integer
  74.      */
  75.     protected $lifetime = 1800;
  76.    
  77.     /**
  78.      * Session cookie path
  79.      *
  80.      * @access protected
  81.      * @var string
  82.      */
  83.     protected $cookie_path = '/';
  84.    
  85.     /**
  86.      * SimpleSessionVars object
  87.      *
  88.      * @access private
  89.      * @var object
  90.      */
  91.     public $data = null;
  92.    
  93.     /**
  94.      * Session ID
  95.      *
  96.      * @access public
  97.      * @var string
  98.      */
  99.     public $id;
  100.    
  101.     /**
  102.      * SimpleSession object constructor
  103.      *
  104.      * @access public
  105.      * @param object SimpleMySQL instance
  106.      * @return void
  107.      *
  108.      * @see SimpleSessionVars
  109.      */
  110.     public function __construct(SimpleMySQL $MySQL) {
  111.        
  112.         if (!extension_loaded('mcrypt'))
  113.             $this->encryption = false;
  114.         else if (!function_exists('mcrypt_module_open'))
  115.             $this->encryption = false;
  116.         else {
  117.             $this->encryption = true;
  118.            
  119.             $key_1 = md5(SESSION_DATA_ENCRYPTION_KEY_1);
  120.             $key_2 = md5(SESSION_DATA_ENCRYPTION_KEY_2);
  121.            
  122.             $this->encryption_key = $key_1.$key_2;
  123.         }
  124.        
  125.         // Save MySQL object and clean its previous results if any
  126.         $this->mysql = $MySQL;
  127.         $this->mysql->clean();
  128.        
  129.         // Set session garbage collector properties
  130.         ini_set('session.gc_divisor', $this->gc_divisor);
  131.         ini_set('session.gc_probability', $this->gc_probability);
  132.         ini_set('session.gc_maxlifetime', $this->gc_maxlifetime);
  133.        
  134.         // Set session id hashing options
  135.         ini_set('session.hash_function', 1);
  136.         ini_set('session.hash_bits_per_character', 5);
  137.        
  138.         // Set handler functions
  139.             array(&$this, '__open'),
  140.             array(&$this, '__close'),
  141.             array(&$this, '__read'),
  142.             array(&$this, '__write'),
  143.             array(&$this, '__destroy'),
  144.             array(&$this, '__gc')
  145.         );
  146.        
  147.         // Call session_write_close() from the object destructor
  148.         @register_shutdown_function(array(&$this, '__destruct'));
  149.     }
  150.    
  151.     /**
  152.      * SimpleSession object destructor
  153.      *
  154.      * @access public
  155.      * @return boolean
  156.      */
  157.     public function __destruct() {
  158.        
  159.         // Call session_write_close() then return true
  160.         session_write_close();
  161.         return true;
  162.     }
  163.    
  164.     public function __open($save_path, $session_name) {
  165.         return true;
  166.     }
  167.    
  168.     public function __close() {
  169.         return true;
  170.     }
  171.    
  172.     public function __read($session_id) {
  173.        
  174.         $session_id = $this->mysql->escape($session_id);
  175.         $session_data = '';
  176.        
  177.         // Build query to retrieve current session data
  178.         $query_sentence = "
  179.             SELECT
  180.                 session_data
  181.             FROM
  182.                 {$this->mysql->tables['sessions']}
  183.             WHERE
  184.                 session_id = '%s'
  185.         ";
  186.         $this->mysql->query(sprintf($query_sentence, $session_id));
  187.        
  188.         // Check if session data is available
  189.         if ($this->mysql->affected_rows > 0) {
  190.             $session_data = $this->mysql->query_result[0]->session_data;
  191.             $session_data = $this->decrypt($session_data);
  192.             $this->mysql->clean();
  193.         }
  194.        
  195.         // If no session data was found, return an empty string
  196.         return (string)$session_data;
  197.     }
  198.    
  199.     public function __write($session_id, $session_data) {
  200.        
  201.         $session_id = $this->mysql->escape($session_id);
  202.         $session_data = $this->encrypt($session_data);
  203.        
  204.         // Build query to write/rewrite current session data into database
  205.         $query_sentence = "
  206.             REPLACE INTO
  207.                 {$this->mysql->tables['sessions']}
  208.                 (session_id, session_data, session_touched)
  209.             VALUES
  210.                 ('%s', '%s', UNIX_TIMESTAMP())
  211.         ";
  212.         $this->mysql->query(sprintf($query_sentence, $session_id, $session_data));
  213.         $this->mysql->clean();
  214.        
  215.         return true;
  216.     }
  217.    
  218.     public function __destroy($session_id) {
  219.        
  220.         $session_id = $this->mysql->escape($session_id);
  221.        
  222.         // Build query to delete the current session from database
  223.         $query_sentence = "
  224.             DELETE FROM
  225.                 {$this->mysql->tables['sessions']}
  226.             WHERE
  227.                 session_id = '%s'
  228.         ";
  229.         $this->mysql->query(sprintf($query_sentence, $session_id));
  230.        
  231.         return true;
  232.     }
  233.    
  234.     public function __gc($session_max_lifetime) {
  235.         $query_sentence = "
  236.             DELETE FROM
  237.                 {$this->mysql->tables['sessions']}
  238.             WHERE
  239.                 session_touched + {$session_max_lifetime} < UNIX_TIMESTAMP()
  240.         ";
  241.         $this->mysql->query($query_sentence);
  242.         return true;
  243.     }
  244.    
  245.     /**
  246.      * Session start
  247.      *
  248.      * @access public
  249.      * @return unknown
  250.      */
  251.     public function start() {
  252.        
  253.         session_name($this->name);
  254.         session_set_cookie_params($this->lifetime, $this->cookie_path);
  255.         session_cache_limiter('nocache');
  256.        
  257.         header("Pragma: no-cache");
  258.         header("Expires: Mon, 28 Aug 1989 02:22:00 GMT");
  259.         header("Last-Modified: " .gmdate("D, d M Y H:i:s"). " GMT");
  260.         header("Cache-Control: no-store, no-cache, must-revalidate");
  261.         header("Cache-Control: post-check=0, pre-check=0", false);
  262.        
  263.         session_start();
  264.        
  265.         $this->id = session_id();
  266.        
  267.         // Create SimpleSessionData object to manipulate session data
  268.         // I.e.: $SimpleSession->data->foo = 'bar' => ($_SESSION['foo'] = 'bar')
  269.         $this->data = new SimpleSessionData;
  270.     }
  271.    
  272.     /**
  273.      * Session destroy
  274.      *
  275.      * @access public
  276.      * @return boolean
  277.      */
  278.     public function destroy() {
  279.        
  280.         // Unset all session variables
  281.         $this->id = null;
  282.         session_unset();
  283.        
  284.         // Delete session cookie, if found
  285.         if (isset($_COOKIE[$this->name]))
  286.             @setcookie($this->name, '', time() - $this->lifetime, $this->cookie_path);
  287.        
  288.         // Destroy the current session
  289.         return session_destroy();
  290.     }
  291.    
  292.     /**
  293.      * Session regenerate ID
  294.      *
  295.      * @access public
  296.      * @param boolean $delete_old_session
  297.      * @return boolean
  298.      */
  299.     public function regenerate_id($delete_old_session = false) {
  300.         if (session_regenerate_id($delete_old_session))
  301.             $this->id = session_id();
  302.         else return false;
  303.     }
  304.    
  305.     /**
  306.      * Session data encrypter
  307.      *
  308.      * @access public
  309.      * @param string $session_data
  310.      * @return string
  311.      */
  312.     private function encrypt($session_data = '') {
  313.        
  314.         if (empty($session_data))
  315.             return $session_data;
  316.        
  317.         if (!$this->encryption)
  318.             return base64_encode($session_data);
  319.        
  320.         $td = mcrypt_module_open('rijndael-256', '', 'ecb', '');
  321.         $ks = mcrypt_enc_get_key_size($td);
  322.        
  323.         $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
  324.         $key = substr($this->encryption_key, 0, $ks);
  325.        
  326.         mcrypt_generic_init($td, $key, $iv);
  327.        
  328.         // Encrypt data
  329.         $encrypted_data = mcrypt_generic($td, $session_data);
  330.        
  331.         mcrypt_generic_deinit($td);
  332.         mcrypt_module_close($td);
  333.        
  334.         return base64_encode($encrypted_data);
  335.     }
  336.    
  337.     /**
  338.      * Session data decrypter
  339.      *
  340.      * @access public
  341.      * @param string $session_data
  342.      * @return string
  343.      */
  344.     private function decrypt($session_data = '') {
  345.        
  346.         if (empty($session_data))
  347.             return $session_data;
  348.        
  349.         $session_data = base64_decode($session_data);
  350.        
  351.         if (!$this->encryption)
  352.             return $session_data;
  353.        
  354.         $td = mcrypt_module_open('rijndael-256', '', 'ecb', '');
  355.         $ks = mcrypt_enc_get_key_size($td);
  356.        
  357.         $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
  358.         $key = substr($this->encryption_key, 0, $ks);
  359.        
  360.         mcrypt_generic_init($td, $key, $iv);
  361.        
  362.         // Decrypt data
  363.         $decrypted_data = mdecrypt_generic($td, $session_data);
  364.        
  365.         mcrypt_generic_deinit($td);
  366.         mcrypt_module_close($td);
  367.        
  368.         $decrypted_data = rtrim($decrypted_data);
  369.        
  370.         return (string)$decrypted_data;
  371.     }
  372. }
  373.  
  374. /**
  375.  * Simple Session Data
  376.  *
  377.  * @package SimpleSession
  378.  * @subpackage SimpleSessionData
  379.  * @author Diego P. M. Baltar <[email protected]>
  380.  * @copyright 2010
  381.  * @version 0.1
  382.  */
  383. class SimpleSessionData {
  384.    
  385.     public function __set($var, $value) {
  386.         $_SESSION[$var] = $value;
  387.     }
  388.    
  389.     public function __get($var) {
  390.         if (!isset($_SESSION[$var]))
  391.             return null;
  392.         else return $_SESSION[$var];
  393.     }
  394.    
  395.     public function __isset($var) {
  396.         return isset($_SESSION[$var]);
  397.     }
  398.    
  399.     public function __unset($var) {
  400.         unset($_SESSION[$var]);
  401.     }
  402. }
  403.  
  404. ?>