Unable to submit data from form containing code to avoid csrf attacks using php

I am trying to pass data in a form that has code that checks for csrf attacks first and then sends dat using php, but the code always tells me that there is an attack even though there is not attack The code always just executes the error message and the rest of the code is not considered.

php code:

    <?php 
$csrf_avoid= bin2hex(random_bytes(20));
 $_SESSION['auth_token'] = $csrf_avoid;                   
if (isset($_POST["save_entry"])) {
                             
if ($_POST["auth_token"] !== $csrf_avoid) {
// show an error message
echo '<h1 class="error">Error: invalid form submission</h1><p>Your request was denied as this request could not be verified.</p>';
                          // return 405 http status code
 exit();
  }
 else{                                                
// do anything here there is no csrf attacks                                                
 }                  
 }              
?>

html

<input type="hidden" name="auth_token" value="<?php echo $csrf_avoid;?>">

>Solution :

first of, don’t generate a token every time, and check the session when submitting :

if(!isset($_SESSION['auth_token'])) {
    $csrf_avoid = bin2hex(random_bytes(20));
    $_SESSION['auth_token'] = $csrf_avoid;     
}
                
if (isset($_POST["save_entry"])) {
    //check the session                          
    if ($_SESSION['auth_token'] !== $csrf_avoid) {
        // show an error message
        echo '<h1 class="error">Error: invalid form submission</h1><p>Your request was denied as this request could not be verified.</p>';
        // return 405 http status code
        exit();
    }
    else {                                                
        // do anything here there is no csrf attacks

        // you could regenerate token on submit, so the current one becomes invalid
        $csrf_avoid = bin2hex(random_bytes(20));
        $_SESSION['auth_token'] = $csrf_avoid;                                                  
    }                  
}

Also change your input to :

<input type="hidden" name="auth_token" value="<?php echo $_SESSION['auth_token'];?>">

Leave a Reply