Form submission can sometimes be triggered unintentionally multiple times in a row, leading to undesired behavior and data inconsistencies. This situation can arise due to various factors, such as button multiple clicks or slow form processing. PHP provides techniques to prevent such multiple submissions, ensuring data integrity.
To combat multiple submissions, a widely used approach involves utilizing a token generated each time a form is displayed. This token is then submitted with the form and validated on the server side. The pivotal benefit of this approach lies in its potential to mitigate both CSRF (Cross-Site Request Forgery) attacks and replay attacks.
The example below demonstrates the creation of a unique token for each form display, along with its validation upon form submission.
<?php session_start(); /** * Generates a unique token for the form * @return string The token */ function getToken(){ $token = sha1(mt_rand()); if(!isset($_SESSION['tokens'])){ $_SESSION['tokens'] = array($token => 1); } else{ $_SESSION['tokens'][$token] = 1; } return $token; } /** * Validates the token and removes it from the list of valid tokens * @param string $token The token * @return bool Validation status */ function isTokenValid($token){ if(!empty($_SESSION['tokens'][$token])){ unset($_SESSION['tokens'][$token]); return true; } return false; } // Check if a form has been submitted $postedToken = filter_input(INPUT_POST, 'token'); if(!empty($postedToken)){ if(isTokenValid($postedToken)){ // Process form } else{ // Handle error } } // Get a token for the currently displayed form $token = getToken(); ?> <form method="post"> <fieldset> <input type="hidden" name="token" value="<?php echo $token; ?>"/> <!-- Form content --> </fieldset> </form>
Combining the token-based approach with a redirect enhances the user experience by ensuring proper backward and forward navigation behavior. By implementing the POST / redirect / GET design pattern, you can prevent accidental resubmission when the user clicks the back button or refreshes the page.
The above is the detailed content of How to Prevent Multiple Form Submissions in PHP?. For more information, please follow other related articles on the PHP Chinese website!