Web progamming and database development

Diary of problems and solutions related to web programming, database development and related technologies and platforms.

How to prevent multiple inserts when submitting a form in PHP?

Include a unique token on each POST. In this case, you would also set a session variable to the token you want to include and then render the token in the form. Once the form is submitted, you re-generate the token. When the submitted token does not match the token in your session, the form has been re-submitted and should be declared invalid.
// 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="" />
    <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
        }
    }
}

No comments :

Post a Comment