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:
<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>
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!