Advertisement
AyrA

_csrf.php

Feb 23rd, 2018
189
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.03 KB | None | 0 0
  1. <?php
  2.  
  3.     //Length in bytes of the CSRF token. It's converted to a hex string so the length will double.
  4.     define("CSRF_TOKEN_SIZE",10);
  5.    
  6.     //Creates or evaulates a CSRF token.
  7.     function csrf_token($value=null){
  8.         //Ensure a token is here
  9.         if(!isset($_SESSION["_csrf"])){
  10.             $_SESSION["_csrf"]=$token=bin2hex(random_bytes(CSRF_TOKEN_SIZE));
  11.         }
  12.         else{
  13.             $token=$_SESSION["_csrf"];
  14.         }
  15.  
  16.         //If no value is provided, return the current token
  17.         if($value===null){
  18.             return $token;
  19.         }
  20.         else{
  21.             //Check token
  22.             return $value===$token;
  23.         }
  24.     }
  25.    
  26.     //Set a specific CSRF token
  27.     function csrf_set($token){
  28.         return $_SESSION["_csrf"]=$token;
  29.     }
  30.    
  31.     //unsets the CSRF token
  32.     function csrf_unset(){
  33.         unset($_SESSION["_csrf"]);
  34.     }
  35.    
  36.     //Check if the submitted CSRF token is valid
  37.     function csrf_check(){
  38.         return isset($_POST["_csrf"]) && csrf_token($_POST["_csrf"]);
  39.     }
  40.    
  41.     //Generates the CSRF token field.
  42.     function csrf_field(){
  43.         return "<input type=\"hidden\" name=\"_csrf\" value=\"".csrf_token()."\" />";
  44.     }
  45. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement