Preventing Multiple Form Submissions with PHP
In web development, it's essential to safeguard against multiple form submissions when a user repeatedly clicks on the submit button. This can lead to unintended results, such as duplicate data entries or unexpected behavior. PHP offers several techniques to prevent this issue.
One effective approach is to utilize unique form tokens. When a form is displayed, a unique token is generated and stored in the session. When the form is submitted, the token is checked against the stored version. If the tokens match, the form submission is processed. If they don't, the submission is rejected, preventing multiple submissions.
Here's a simple PHP implementation:
session_start(); function getToken() { $token = sha1(mt_rand()); if (!isset($_SESSION['tokens'])) { $_SESSION['tokens'] = array($token => 1); } else { $_SESSION['tokens'][$token] = 1; } return $token; } function isTokenValid($token) { if (!empty($_SESSION['tokens'][$token])) { unset($_SESSION['tokens'][$token]); return true; } return false; } $postedToken = filter_input(INPUT_POST, 'token'); if (!empty($postedToken)) { if (isTokenValid($postedToken)) { // Process form } else { // Handle error } } $token = getToken();
<form method="post"> <fieldset> <input type="hidden" name="token" value="<?php echo $token; ?>" /> <!-- Add form content --> </fieldset> </form>
To enhance security, combine this token validation with a redirect on form submission. This ensures that when a user presses the back button, a new form is displayed with a fresh token. This pattern, known as POST / redirect / GET, further prevents multiple submissions and maintains backward and forward compatibility.
The above is the detailed content of How to Prevent Multiple Form Submissions with PHP?. For more information, please follow other related articles on the PHP Chinese website!