Full Stack LAMP - MEAN Developer, Python developer. Certified Azure Developer. Freelance programmer/consultant/trainer.

How to prevent multiple form submissions in PHP?

In this post, we gonna see how we can prevent multiple submissions of a form in PHP applications.

Sometimes a user may hit submit button twice or the user may reload the page(with post data), both activities make form processing multiple times with the same data, this results in duplicate records in DB or duplicate Emails in the Inbox.

In order to avoid this behavior in PHP, we will include a unique token on each post request this method is also useful to prevent CSRF and replay attacks. we will include generated unique key in the form, hidden field, and in a session variable. Once the form is submitted we will compare the hidden field value with the session token value, if both values match the form submission is valid, if the token does not match the token in your session, the form has been re-submitted.

How to generate a token

In this example, the PHP function uniqid() is used to generate the form token value.

<?php
        // start the session
        session_start();
        // form token 
        $form_token = uniqid();

        // create form token session variable and store generated id in it.
        $_SESSION['form_token'] = $form_token;
?>

Show me the Logic

just copy the above code and past it to the form page. then create a hidden field inside the form as shown below

<input name="token" type="hidden" value="<?php echo $form_token; ?>">

In the form process page, we will compare the token as shown below

if($_POST['form_token'] != $_SESSION['form_token']) {
   echo 'form resubmitted!'; exit;
} else {
 do ...
}

Complete Example

Below is the completed sample script for preventing multiple form submissions in PHP.

<?php
/*** begin the session ***/
session_start();

/*** create the form token ***/
$form_token = uniqid();

/*** add the form token to the session ***/
$_SESSION['form_token'] = $form_token;
?>
<!DOCTYPE html>
    <head>
        <title>My Form</title>
    </head>
<body>
    <form action="process.php" method="post">
        <input type="hidden" name="form_token" value="<?php echo $form_token; ?>" />
        <div>
            <label for="name">Name</label>
            <input type="text" name="name" />
        <div>
        <div>
            <input type="submit" value="Add Name" />
        </div>
    </form>
</body>
</html>

Create process.php file and place the below code in it.

<?php
//process.php 
 
// start session
session_start();

if($_POST['form_token'] != $_SESSION['form_token'])
{
    echo 'Access denied';
} else {
    print_r($_POST);
// do your logic
}

$_SESSION['form_token'] = "";

I hope it helps you guys to prevent multiple form submissions.

Do share it and let your friends know about it.

  1. I was looking for a solution like this, although this code doesn’t work. You don’t regenerate $form_token. You always post $form_token and it always ends up in the else clause. Do you have any fix for this?

      1. You should try it with a larger form and do some checks if fields are set. I use it with a quite large form that takes a few seconds to submit and write the data to the database. The idea is fantastic, and it works. But I think it only works because you have a very small form, and you simply don’t have the time to do a doubleclick. At least that’s my observation.

  2. I don’t see how this would prevent the scenario where a user refreshes the page that processed the submitted data causing the submitted data to be processed again. The token in session will still be the same as the token that was submitted.

  3. To make this work you need to unset the session value after the form is submitted the first time: unset($_SESSION[‘form_token’]); Otherwise the user can press F5 or otherwise refresh the page and submit the same data again.

  4. Works like a charm, thanks!

    Beggining of the page:

    <?php

    if($_POST[“token”] == $_SESSION[“token”]) {

    your code

    }


    your code

    $_SESSION[“token”] = uniqid();

    ?>

    <form>

    your code

    <input name=”token” type=”hidden” value=”<?= $_SESSION[‘token’]; ?>”>
    </form>

Leave a Reply