I'm struggling to understand an answer on SO. It's a solution which prevents the form from being processed twice (if someone clicks "submit" button twice in a row).
It generates a unique token and stores it in the form. So if the submit button is clicked twice it will ignore the duplicate submission.
Code is
// form.php
<?php
// obviously this can be anything you want, as long as it is unique
$_SESSION['token'] = md5(session_id() . time());
?>
<form action="foo.php" method="post">
<input type="hidden" name="token" value="<?php echo $_SESSION['token'] ?>" />
<input type="text" name="bar" />
<input type="submit" value="Save" />
</form>
// foo.php
if (isset($_SESSION['token']))
{
if (isset($_POST['token']))
{
if ($_POST['token'] != $_SESSION['token'])
{
// double submit
}
}
}
Everyone agrees that it's the right solution, but I don't understand why the $_SESSION['token'] changes the second time we click the submit button.
Thank you for your help
$_SESSION['token'] = md5(session_id() . time());
– Jay Blanchard Jul 30 '18 at 17:41$_POST['token'] === $_SESSION['token']
you change the token in the session so that if the form was submitted twice, the same token is posted twice, changed on the first submit and doesn't match on the second. – Jonathan Jul 30 '18 at 17:41==
usehash_equals()
– Rotimi Jul 30 '18 at 17:43