Prevent multiple form submission

Are you tired of people submitting the same information via your online forms multiple times and cluttering up your database and mail? If yes, this PHP snippet could be your solution. With this function (and native PHP session support) it’s possible to prevent a multiple form submission while using some server side form field validation. The script checks the unique string from the current submission against the post before and will stop if the submitted form or string is the same as before.

function prevent_multi_submit($type = "post", $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 .= $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;
    }
}

Example / how-to use the PHP snippet

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

You should use the script together with some client side functions (JavaScript)