shibbir ahmed
shibbir ahmed

Reputation: 1024

How can validate multiple form In one page using form token to prevent CSRF Attacks?

Well, In my website I am using PHP unique form token to prevent CSRF attacks. The unique form token and form token validation function is bellow :

// generate new token for every form
function generate_Form_Token($form_name) {        
    $token = md5(uniqid(microtime(), true));                  
    $_SESSION[$form_name.'_token'] = $token; 
    return $token;
}

// validate form request
function verifyForm ($form, $url){
    // call the form processing page
    $actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";   
    if($actual_link !== SITE_URL."$url") 
        return false;    
    if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) !== 'xmlhttprequest')
        return false;      
    if(!isset($_SESSION[$form.'_token']))
        return false;
    if(!isset($_POST['_token']))
        return false;
    if($_SESSION[$form.'_token'] !== $_POST['_token'])
        return false;

    return true;
}

Now If I have one form in one page then it's validating the form successfully.

BUT in my website I have a page called create-menu.php Here I am using 4 form So this 4 form will generate 4 unique form token and I am use following input field to every 4 form :

<input type="hidden" name="_token" value="<?php echo generate_Form_Token('menu_creation'); ?>">

But the problem is when I validating the form (Using Ajax) in process.php page. In this page only 1st form is validating but other 3 form is showing me error message (my custom error message if the form token is not match with session).

process.php page

if($_SERVER['REQUEST_METHOD'] == 'POST') {
    if(verifyForm('menu_creation','menu-creation')) {
    // my code.....
    }
}

How can I solved this type of issue ? Can anyone assist me with that ? Thank You.

Upvotes: 0

Views: 315

Answers (1)

Quentin
Quentin

Reputation: 943593

Call the function that generates the token once. Store the return value in a variable. Use that variable in each form.

Upvotes: 1

Related Questions