How to Prevent Multiple Inserts When Submitting Forms in PHP?

Linda Hamilton
Release: 2024-10-21 21:32:02
Original
852 people have browsed it

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:

    <code class="php">// form.php
    $_SESSION['token'] = md5(session_id() . time());
    
    echo '<form action="foo.php" method="post">
           <input type="hidden" name="token" value="' . $_SESSION['token'] . '" />
           <input type="text" name="bar" />
           <input type="submit" value="Save" />
        </form>';
    
    // foo.php
    if (isset($_SESSION['token'])) {
        if (isset($_POST['token']) && $_POST['token'] != $_SESSION['token']) {
            // Double submit detected
        }
    }</code>
    Copy after login

By implementing one of these methods, you can effectively prevent multiple inserts when submitting forms in PHP, ensuring data integrity and avoiding unintentional duplication.

The above is the detailed content of How to Prevent Multiple Inserts When Submitting Forms in PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!