Categorized | PHP

How do you use PHP Sessions to prevent forms from being submitted twice?

Posted on 06 June 2010 by Abidoon

I want to prevent a form from being submitted a second time when a user presses the back button.

Tags | , , , , , ,

2 Responses to “How do you use PHP Sessions to prevent forms from being submitted twice?”

  1. leejw00t354 says:

    Umm im not sure if theirs a standered way of doing this but you might want to try on the page the form is submited on:
    if($_SESSION['submit']){
    echo “You have already submitted this form”;
    }
    if(isset($_POST['submit'])){
    $_SESSION['submit'] = true;
    }

  2. Zilk says:

    1) generate a random string, like “8fd331d2″
    $random_token = dechex(rand());

    2) remember all the strings that you generate in the session:
    $_SESSION["tokens"][$random_token] = 1;

    3) add the token as a hidden field to the form, like

    if (!empty($_SESSION["tokens"][ $value_from_hidden_field])) {
    // it’s still there, this means that the form has been submitted
    // for the first time. delete the used up token from the session
    unset($_SESSION["tokens"][ $value_from_hidden_field]);
    // —> it’s ok to process the form values now
    } else {
    // it’s gone, this means we’ve already removed it because the
    // form has been submitted before
    // —> ignore the submitted values.
    }

    Hope that helps!


Leave a Reply