Guarding Against Multiple Submissions of the Same Form

The way to prevent a user from submitting the same form more than once

Posted on April 26, 2016 in PHP

Include a hidden field in the form with a unique value. When validating the form, check if a form has been submitted with that value. If it has, reject the submission. If it hasn’t, process the form and record the value for later use. Additionally, use JavaScript to disable the form Submit button once the form has been submitted.

We use the uniqid() and md5() functions to insert a unique ID field in a form.


<form method="post" action="<?php echo $_SERVER['SCRIPT_NAME'] ?>" onsubmit="document.getElementById('submit-button').disabled = true;">
    <!-- insert all the normal form elements you need -->
    <input type="hidden" name="token" value="<?php echo md5(uniqid()) ?>"/>
    <input type="submit" value="Save Data" id="submit-button" />
</form>

We checks the submitted token against saved data in the database to see if the form has already been submitted.


$db = new PDO('mysql:unix_socket=/tmp/mysql.sock', $user, $password);
$db->beginTransaction();
$sth = $db->prepare('SELECT * FROM forms WHERE toke = ?');
$sth->execute(array($_POST['token']));

if(count($sth->fetchAll())) {
    print "This form has already been submitted!";
    $db->rollBack();
}
else {
    // Validation code for the rest of the form 
    $sth = $db->prepare('INSERT INTO forms (token) VALUES (?)');
    $sth->execute(array($_POST['token']));
    $db->commit();
    print "The form is submitted successfully.";
}


comments powered by Disqus