How to prevent multiple form submissions in PHP
A problem that many programmers encounter is trying to prevent the user from submitting a form twice and inadvertently posting two sets of the same data – or in worse scenarios, charging a credit card twice!
It’s a frustrating problem that is easily solved if you put your mind to it – ignoring it is nothing short of lazy.
On the client-side, we can use JavaScript to prevent the user from submitting the form more than once. Observe:
<form action="script.php" method="post" onclick="validateForm();">
Your name? <input name="name" value=""> <input type="submit">
</form>
<script type="text/javascript">
var submitted=false;
function validateForm() {
if (submitted) {
alert("Please only submit the form once.");
return false;
} else {
return true;
}
}
</script>
The idea is that when the user clicks the submit button, we flag the action in ‘submitted’. If the user clicks again, the function validateForm() will check ‘submitted’ and prevent multiple submissions of the form.
But this isn’t enough – not everybody has JavaScript enabled, and assuming so would be lazy.
We need some internal detection too, and one way to detect multiple submissions would be to use PHP sessions. Observe:
<?php
session_start();
if ($_SESSION['formsessions'][$_POST['formsession']]) {
// form already submitted!
// ideally, at this point, you'd want to forward them to another page.
exit('form submitted twice.')
}
// mark the session as submitted.
$_SESSION['formsessions'][$_POST['formsession']]=true;
?>
Again, we’re checking to see if the form has already been submitted. This script would require that we submit a ‘formsession’ field with the form to make it uniquely identifiable. This could be as easy as inserting the following into the form code:
<?php
echo '<input type="hidden" name="formsession" value="'.md5(date('U').'-'.rand(1000000,9999999)).'">';
?>
With these two methods combined, no user should be able to submit the same form twice – accidentally, at least.