carlos1993

SESSION HANDLING PDO

Jun 24th, 2013
241
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 8.22 KB | None | 0 0
  1. <?php
  2. /*
  3.  * Secure Session Mgmt
  4.  */
  5.     class _session {
  6.         private $_connection; //Connection settings (Must be a PDO object)
  7.        
  8.         private $r_stmt;// Variable to store the read statement
  9.         private $w_stmt;// Variable to store the write statement
  10.         private $delete_stmt;// Variable to store the delete statement
  11.         private $gc_stmt; //Variable to store the Garbage collection statement s
  12.         private $key_stmt; //Variable to store the get key stmt
  13.        
  14.         function __construct(&$connection) {
  15.             //Set connection
  16.             $this->_connection = $connection;
  17.             // set our custom session functions.
  18.             session_set_save_handler(
  19.                     array($this, 'open'),
  20.                     array($this, 'close'),
  21.                     array($this, 'read'),
  22.                     array($this, 'write'),
  23.                     array($this, 'destroy'),
  24.                     array($this, 'gc'));
  25.  
  26.             // This line prevents unexpected effects when using objects as save handlers.
  27.             register_shutdown_function('session_write_close');
  28.          }
  29.          public function start_session($session_name, $secure) {
  30.             // Make sure the session cookie is not accessable via javascript.
  31.             $httponly = true;
  32.  
  33.             // Hash algorithm to use for the sessionid. (use hash_algos() to get a list of available hashes.)
  34.             $session_hash = 'sha512';
  35.  
  36.             // Check if hash is available
  37.             if (in_array($session_hash, hash_algos())) {
  38.                // Set the has function.
  39.                ini_set('session.hash_function', $session_hash);
  40.             }
  41.             // How many bits per character of the hash.
  42.             // The possible values are '4' (0-9, a-f), '5' (0-9, a-v), and '6' (0-9, a-z, A-Z, "-", ",").
  43.             ini_set('session.hash_bits_per_character', 5);
  44.  
  45.             // Force the session to only use cookies, not URL variables.
  46.             ini_set('session.use_only_cookies', 1);
  47.  
  48.             // Get session cookie parameters
  49.             $cookieParams = session_get_cookie_params();
  50.             // Set the parameters
  51.             session_set_cookie_params($cookieParams["lifetime"], $cookieParams["path"], $cookieParams["domain"], $secure, $httponly);
  52.             // Change the session name
  53.             session_name($session_name);
  54.             // Now we cat start the session
  55.             session_start();
  56.             // This line regenerates the session and delete the old one.
  57.             // It also generates a new encryption key in the database.
  58.             session_regenerate_id(true);    
  59.          }
  60.          public function open (){
  61.              //Connection have already being set
  62.             return true;
  63.          }
  64.          public function close(){
  65.              //Connection can be unset by declaring the connection object to null
  66.              //Or simply unset($connection)
  67.              return true;
  68.          }
  69.          public function read($id){
  70.              $qry = "SELECT data
  71.                     FROM sessions
  72.                     WHERE id = :id";
  73.              //Prepare the qry only one time
  74.              if (!isset($this->r_stmt)){
  75.                  $this->r_stmt = $this->_connection->prepare($qry);
  76.              }
  77.              $this->r_stmt->bindParam(':id', $id, PDO::PARAM_INT);
  78.              if($this->r_stmt->execute()){
  79.                  //Fetch only one row from DB as $row ['data']
  80.                 $row = $this->r_stmt->fetch(PDO::FETCH_ASSOC);
  81.                 $key = $this->getkey($id);
  82.                 $data = $this->decrypt($row['data'], $key);
  83.                 return $data;
  84.              }
  85.              else{
  86.                  echo "Something went wrong! read();";
  87.                  return false;
  88.              }
  89.          }
  90.          public function write($id, $data) {
  91.             // Get unique key
  92.             $key = $this->getkey($id);
  93.             // Encrypt the data
  94.             $data = $this->encrypt($data, $key);
  95.             $time = time();
  96.             $qry  = "REPLACE
  97.                    INTO sessions (id,data,session_key,set_time)
  98.                    VALUES (:id,:data,:session,:time)";
  99.             if(!isset($this->w_stmt)) {
  100.                $this->w_stmt = $this->_connection->prepare($qry);
  101.             }
  102.  
  103.             $this->w_stmt->bindParam(':id', $id, PDO::PARAM_INT);
  104.             $this->w_stmt->bindParam(':time', $time, PDO::PARAM_STR);
  105.             $this->w_stmt->bindParam(':data', $data, PDO::PARAM_STR);
  106.             $this->w_stmt->bindParam(':session', $key, PDO::PARAM_STR);
  107.            
  108.             if($this->w_stmt->execute()){
  109.                 return true;
  110.             }
  111.             else{
  112.                 echo "Something went wrong! write();";
  113.                 return false;
  114.             }
  115.            
  116.          }
  117.          public function destroy($id) {
  118.              $qry ="DELETE
  119.                 FROM sessions
  120.                 WHERE id = :id";
  121.             if(!isset($this->delete_stmt)) {
  122.                $this->delete_stmt = $this->_connection->prepare($qry);
  123.             }
  124.             $this->delete_stmt->bindParam(':id', $id, PDO::PARAM_INT);
  125.            
  126.             if($this->delete_stmt->execute()){
  127.                 return true;
  128.             }
  129.             else{
  130.                 echo "Something went wrong! delete();";
  131.                 return false;
  132.             }
  133.          }
  134.          public function gc($max) {
  135.              $qry  = "DELETE
  136.                      FROM sessions
  137.                      WHERE set_time < :max";
  138.             if(!isset($this->gc_stmt)) {
  139.                $this->gc_stmt = $this->_connection->prepare($qry);
  140.             }
  141.             $old = time() - $max;
  142.             $this->delete_stmt->bindParam(':old', $old, PDO::PARAM_INT);
  143.             if($this->gc_stmt->execute()){
  144.                 return true;
  145.             }
  146.             else{
  147.                 echo "Something went wrong! gbc();";
  148.                 return false;
  149.             }
  150.          }
  151.          private function getkey($id) {
  152.             $qry = "SELECT session_key
  153.                FROM sessions
  154.                WHERE id = :id LIMIT 1";
  155.             if(!isset($this->key_stmt)) {
  156.                $this->key_stmt = $this->_connection->prepare($qry);
  157.             }
  158.             $this->key_stmt->bindParam(':id', $id, PDO::PARAM_INT);
  159.             if($this->key_stmt->execute()){
  160.                $row = $this->r_stmt->fetch(PDO::FETCH_ASSOC);
  161.                if(count($row) != 1){
  162.                     return $row['session_key'];
  163.                }
  164.                else {
  165.                    $random_key = hash('sha512', uniqid(mt_rand(1, mt_getrandmax()), true));
  166.                    return $random_key;
  167.                }
  168.             }
  169.             else {
  170.                echo "Something went wrong! getkey();";
  171.                return false;
  172.             }
  173.          }
  174.          private function encrypt($data, $key) {
  175.             $salt = 'cH!swe!retReGu7W6bEDRup7usuDUh9THeD2CHeGE*ewr4n39=E@rAsp7c-Ph@pH';
  176.             $key = substr(hash('sha256', $salt.$key.$salt), 0, 32);
  177.             $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
  178.             $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
  179.             $encrypted = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $data, MCRYPT_MODE_ECB, $iv));
  180.             return $encrypted;
  181.          }
  182.         private function decrypt($data, $key) {
  183.            $salt = 'cH!swe!retReGu7W6bEDRup7usuDUh9THeD2CHeGE*ewr4n39=E@rAsp7c-Ph@pH';
  184.            $key = substr(hash('sha256', $salt.$key.$salt), 0, 32);
  185.            $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
  186.            $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
  187.            $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, base64_decode($data), MCRYPT_MODE_ECB, $iv);
  188.            return $decrypted;
  189.         }
  190.          
  191.     }
  192.        
  193.     //Connection Details
  194. $db_host = "localhost";
  195. $db_user = "root";
  196. $db_password = "";
  197. $db_database = "";
  198. $pdo = new PDO("mysql:host=$db_host;dbname=$db_database;charset=utf8", $db_user, $db_password);
  199.  $session = new _session($pdo);
  200. // Set to true if using https
  201. $session->start_session('_s', false);
  202.  
  203. $_SESSION['something'] = 'password';
  204. echo $_SESSION['something'];
  205. ?>
Add Comment
Please, Sign In to add comment