Debounce refers to allowing only one execution of an event handler when a user triggers an event multiple times rapidly, and blocking further executions within a certain time after the last trigger. In web development, preventing duplicate form submissions is crucial because repeated submissions can cause data redundancy, increased server load, and logical errors.
A simple and effective way is to use Session to record the timestamp of the user’s last submission. By comparing the current time with the last submission time interval, you can decide whether to allow further submission. The following example shows the implementation:
// Start Session session_start(); <p>// Get current timestamp<br> $currentTimestamp = time();</p> <p>// Get last submission timestamp<br> $lastTimestamp = $_SESSION['lastTimestamp'] ?? 0;</p> <p>// Check if time interval is less than debounce time (e.g., 5 seconds)<br> if ($currentTimestamp - $lastTimestamp < 5) {<br> echo 'Please do not submit repeatedly';<br> exit;<br> }</p> <p>// Update last submission timestamp<br> $_SESSION['lastTimestamp'] = $currentTimestamp;<br>
This code prevents users from submitting the form repeatedly within the set interval. Make sure to call session_start() at the beginning of your script to enable Session support.
Another more secure debounce method is using Tokens. Each time the form is rendered, generate a unique Token stored in the Session and inserted as a hidden field in the form. When submitting, the backend verifies if the Token matches to determine if the submission is duplicate.
// Start Session session_start(); <p>// Generate unique Token<br> $token = md5(uniqid(rand(), true));</p> <p>// Store Token in Session<br> $_SESSION['token'] = $token;</p> <p>// Output hidden field in the form with Token<br> echo '<input type="hidden" name="token" value="' . $token . '">';</p> <p>// Verify Token on form submission<br> if ($_POST['token'] !== $_SESSION['token']) {<br> echo 'Please do not submit repeatedly';<br> exit;<br> }</p> <p>// Continue processing form data<br> // ...<br>
This method effectively prevents duplicate form submissions and is difficult to forge. It suits scenarios that require stricter data protection.
With these two approaches—Session timestamp control and Token validation—PHP developers can flexibly implement debounce functionality to effectively avoid problems caused by users submitting forms repeatedly. You can choose the appropriate method based on your project needs and security requirements. Hopefully, the above examples provide practical references for your development.