How to Implement Debounce and Prevent Duplicate Submissions in PHP
This guide explains how to use PHP sessions to create a debounce function that limits rapid event firing and a token‑based mechanism that stops users from submitting the same form multiple times, complete with step‑by‑step code examples.
Debounce Function Implementation
Debounce ensures that a specific operation runs only once within a defined time window. In PHP, the session can store a timer to achieve this.
Create a file named debounce.php with the following content:
<?php
session_start();
function debounce($callback, $delay = 1000) {
if (isset($_SESSION['debounce_timer'])) {
return;
}
$callback();
$_SESSION['debounce_timer'] = time() + $delay;
register_shutdown_function('debounce_reset_timer');
}
function debounce_reset_timer() {
unset($_SESSION['debounce_timer']);
}Use the debounce() function to wrap any event, such as an AJAX request triggered by user input:
<?php
function handleInput() {
// Process AJAX request
}
debounce('handleInput', 1000);Here, handleInput() is the function that processes the request, and 1000 represents a 1‑second debounce delay. Rapid consecutive inputs will result in only the final call being executed.
Anti‑Duplicate Submission Implementation
To prevent users from submitting the same form repeatedly, generate a unique token stored in the session and embed it as a hidden field in the form.
<?php
session_start();
function generateToken() {
$_SESSION['submit_token'] = md5(uniqid(rand(), true));
return $_SESSION['submit_token'];
}
$token = generateToken();Insert the token into the form as a hidden input:
<input type="hidden" name="submit_token" value="<?php echo $token; ?>">When processing the form, validate the submitted token against the one stored in the session:
<?php
session_start();
function validateToken($token) {
if (isset($_SESSION['submit_token']) && $token === $_SESSION['submit_token']) {
unset($_SESSION['submit_token']);
return true;
}
return false;
}
if ($_POST && validateToken($_POST['submit_token'])) {
// Handle form submission logic
}If the tokens match, the form is processed; otherwise, the request is identified as a duplicate submission and can be handled accordingly (e.g., display a warning to the user).
By combining session storage with a debounce timer and a token‑based verification, PHP developers can effectively control rapid event firing and prevent duplicate form submissions.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
php Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
