"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Prevent Multiple Inserts When Submitting Forms in PHP?

How to Prevent Multiple Inserts When Submitting Forms in PHP?

Published on 2024-11-08
Browse:433

How to Prevent Multiple Inserts When Submitting Forms in PHP?

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:

  1. 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.

  2. 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.

  3. 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.

Release Statement This article is reprinted at: 1729517478 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

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