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.
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