Preventing Multiple Inserts on Form Submission in PHP
Multiple inserts when submitting a form can occur when the user presses the submit button multiple times. This can lead to unintended data duplication. There are several approaches to address this issue:
JavaScript Submit Button Disabling:
This method uses JavaScript to disable the submit button after it is clicked. However, it is not reliable as forms can be submitted without using the button or with JavaScript disabled.
PHP Session Timestamp:
This approach sets a session variable ($_SESSION['posttimer']) to the current timestamp upon form submission. During form processing, it checks if the variable exists and compares it to the current timestamp. If the time difference is less than a predefined threshold (e.g., 2 seconds), a double submission is detected.
Unique Token Inclusion:
This method involves including a unique token in each form. A session variable holds the token used in the form. Upon form submission, a new token is generated. If the submitted token doesn't match the session token, it is considered a double submission. Example:
// form.php
$_SESSION['token'] = md5(session_id() . time());
echo '';
// foo.php
if (isset($_SESSION['token'])) {
if (isset($_POST['token']) && $_POST['token'] != $_SESSION['token']) {
// Double submit detected
}
}
By implementing one of these methods, you can effectively prevent multiple inserts when submitting forms in PHP, ensuring data integrity and avoiding unintentional duplication.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3