Punkbastard

Secure PHP Session - PHP

Apr 14th, 2016
314
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.10 KB | None | 0 0
  1. /**
  2.  * Our custom way of starting a secure session
  3.  *
  4.  * Preventing session ID passing as a GET parameter, only send (session)cookie over HTTPS,
  5.  * protection against XSS attacks (HTTP Only), session fixation and session hijacking.
  6.  */
  7. function sec_session_start() {
  8.     // Forces sessions to only use cookies (disallow session ID passing as a GET parameter).
  9.     if (ini_set('session.use_only_cookies', 1) === FALSE) {
  10.         echo "Could not initiate a safe session (ini_set)";
  11.         exit();
  12.     }
  13.  
  14.     $session_name = "xIhFr7bkA5d1y6"; // Set your custom session name.
  15.     $domain = ".mydomain.com"; // The dot makes the (session)cookie available for subdomains too. Change to your domain.
  16.     $secure = TRUE; // If TRUE, (session)cookie will only be sent over secure (HTTPS) connections.
  17.     $http_only = TRUE; // If TRUE, prevents JavaScript being able to access the session id.
  18.  
  19.     // Gets current cookies params.
  20.     $cookieParams = session_get_cookie_params();
  21.     session_set_cookie_params($cookieParams["lifetime"], $cookieParams["path"], $domain, $secure, $http_only);
  22.  
  23.     // Sets the session name to the one set in config
  24.     session_name($session_name);
  25.  
  26.     // Start the PHP session
  27.     session_start();
  28.  
  29.     // Protection against session fixation and hijacking attacks.
  30.     if (!isset($_SESSION['canary'])) {
  31.         session_regenerate_id(true);
  32.         $_SESSION['canary'] = [
  33.             'birth' => time(),
  34.             'browser' => hash('md5', $_SERVER['HTTP_USER_AGENT'])
  35.         ];
  36.     }
  37.     if ($_SESSION['canary']['browser'] !== hash('md5', $_SERVER['HTTP_USER_AGENT'])) {
  38.         session_regenerate_id(true);
  39.         // Delete everything:
  40.         foreach (array_keys($_SESSION) as $key) {
  41.             unset($_SESSION[$key]);
  42.         }
  43.         $_SESSION['canary'] = [
  44.             'birth' => time(),
  45.             'browser' => hash('md5', $_SERVER['HTTP_USER_AGENT'])
  46.         ];
  47.     }
  48.     // Regenerate session ID every five minutes:
  49.     if ($_SESSION['canary']['birth'] < time() - 300) {
  50.         session_regenerate_id(true);
  51.         $_SESSION['canary']['birth'] = time();
  52.     }
  53. }
Add Comment
Please, Sign In to add comment