AyrA icon

_csrf.php

AyrA | PRO | 02/23/18 11:48:21 PM UTC | 0 ⭐ | 484 👁️ | Never ⏰ | []
PHP |

1.03 KB

|

None

|

0 👍

/

0 👎

<?php
 
    //Length in bytes of the CSRF token. It's converted to a hex string so the length will double.
    define("CSRF_TOKEN_SIZE",10);
    
    //Creates or evaulates a CSRF token.
    function csrf_token($value=null){
        //Ensure a token is here
        if(!isset($_SESSION["_csrf"])){
            $_SESSION["_csrf"]=$token=bin2hex(random_bytes(CSRF_TOKEN_SIZE));
        }
        else{
            $token=$_SESSION["_csrf"];
        }
 
        //If no value is provided, return the current token
        if($value===null){
            return $token;
        }
        else{
            //Check token
            return $value===$token;
        }
    }
    
    //Set a specific CSRF token
    function csrf_set($token){
        return $_SESSION["_csrf"]=$token;
    }
    
    //unsets the CSRF token
    function csrf_unset(){
        unset($_SESSION["_csrf"]);
    }
    
    //Check if the submitted CSRF token is valid
    function csrf_check(){
        return isset($_POST["_csrf"]) && csrf_token($_POST["_csrf"]);
    }
    
    //Generates the CSRF token field.
    function csrf_field(){
        return "<input type=\"hidden\" name=\"_csrf\" value=\"".csrf_token()."\" />";
    }
?>

Comments

  •  icon
    01/01/70 12:00:00 AM UTC
    Plain Text |

    0 B

    |

    👍

    /

    👎