Preventing form resubmission

前端 未结 12 1073

Page one contains an HTML form. Page two - the code that handles the submitted data.

The form in page one gets submitted. The browser gets redirected to page two. P

12条回答
  •  不知归路
    2020-11-22 10:00

    Try tris:

    function prevent_multi_submit($excl = "validator") {
        $string = "";
        foreach ($_POST as $key => $val) {
        // this test is to exclude a single variable, f.e. a captcha value
        if ($key != $excl) {
            $string .= $key . $val;
        }
        }
        if (isset($_SESSION['last'])) {
        if ($_SESSION['last'] === md5($string)) {
            return false;
        } else {
            $_SESSION['last'] = md5($string);
            return true;
        }
        } else {
        $_SESSION['last'] = md5($string);
        return true;
        }
    }
    

    How to use / example:

    if (isset($_POST)) {
        if ($_POST['field'] != "") { // place here the form validation and other controls
        if (prevent_multi_submit()) { // use the function before you call the database or etc
            mysql_query("INSERT INTO table..."); // or send a mail like...
            mail($mailto, $sub, $body); // etc
        } else {
            echo "The form is already processed";
        }
        } else {
        // your error about invalid fields
        }
    }
    

    Font: https://www.tutdepot.com/prevent-multiple-form-submission/

提交回复
热议问题