9.5. Guarding Against Multiple Submission of the Same Form

Problem

You want to prevent people from submitting the same form multiple times.

Solution

Generate a unique identifier and store the token as a hidden field in the form. Before processing the form, check to see if that token has already been submitted. If it hasn’t, you can proceed; if it has, you should generate an error.

When creating the form, use uniqid( ) to get a unique identifier:

<?php
$unique_id = uniqid(microtime(),1);
...
?>
<input type="hidden" name="unique_id" value="<?php echo $unique_id; ?>">
</form>

Then, when processing, look for this ID:

$unique_id  = $dbh->quote($_GET['unique_id']);
$sth = $dbh->query("SELECT * FROM database WHERE unique_id = $unique_id");

if ($sth->numRows( )) {
    // already submitted, throw an error
} else {
   // act upon the data
}

Discussion

For a variety of reasons, users often resubmit a form. Usually it’s a slip-of-the-mouse: double-clicking the Submit button. They may hit their web browser’s Back button to edit or recheck information, but then they re-hit Submit instead of Forward. It can be intentional: they’re trying to stuff the ballot box for an online survey or sweepstakes. Our Solution prevents the nonmalicious attack and can slow down the malicious user. It won’t, however, eliminate all fraudulent use: more complicated work is required for that.

The Solution does prevent your database from being cluttered with too many copies of the same record. By generating a token that’s placed ...

Get PHP Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.