Domanda

I have the following code which should prevent form spoofing. A token is used to match and ensure that the form submitted is from that page..

if (isset($_POST['Submit'])) {
    if (!isset($_POST['token']) || $_POST['token'] != $_SESSION['token']) {
        // error, form spoofing, return to users' page or do something else
        echo '<script>',
                 'alert("Form spoofing error!! Please Try again later")',
             '</script>';
    } else {
        //Continue with submission
    }
}

The error shows up every-time I submit the form and needs to show only when there a security risk.

Thanks.

EDIT: The following code is added at the start of the page:

$_SESSION['token'] = md5(time()); 

A hidden field is added which matches with the token created at the start of the session after submission:

<input name="token" id="token" value="<?php echo md5(time()); ?>" type="hidden">

PHP spoofing error comes after every form submission which doesn't let me submit form.

È stato utile?

Soluzione

Heres an example that you can try, it expects the page tobe loaded at least once first before a POST request, also token key is also hashed for fun:

<?php 
session_start();

if ($_SERVER['REQUEST_METHOD']=='POST') {

    if (!isset($_SESSION['token_key']) || 
        !isset($_SESSION['token'])     || 
        !isset($_POST[$_SESSION['token_key']]) || 
        $_POST[$_SESSION['token_key']] != $_SESSION['token']) {

        echo 'Form spoofing error!';
    } else {
        //Continue with validation ect
        echo 'alls good!';
    }
}
//set after any checks on previous values
$_SESSION['token_key'] = sha1(microtime(true));
$_SESSION['token'] = sha1(microtime(true)+1);
?>
<form method="POST" action="">
    <input type="hidden" name="<?php echo $_SESSION['token_key'];?>" value="<?php echo $_SESSION['token'];?>" />
    <p><input type="text" name="yada" size="20">
    <input type="submit" value="Submit" name="B1"></p>
</form>

hope it helps

Altri suggerimenti

You should also consider adding a salt to your hash, because with your method is someone was able to find the time the script was run, they could just take a hash of it and spoof your token. With an added salt they would also need to know the salt.

md5(time()+53498238923);

Just any random number will do for this.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top