Multiple Click Form Submission Prevention in PHP
In web applications, preventing multiple form submissions can enhance user experience and data integrity. PHP offers a solution to address this issue.
Solution: Unique Token
PHP utilizes unique tokens, generated each time a form is displayed. This token can be used only once. Implementing a token system not only prevents multiple form submissions but also safeguards against Cross-Site Request Forgery (CSRF) and replay attacks.
Implementation Example:
<?php session_start(); // Function to create a unique token function getToken() { $token = sha1(mt_rand()); $_SESSION['tokens'][$token] = 1; return $token; } // Function to validate a token function isTokenValid($token) { if (isset($_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 ($postedToken) { if (isTokenValid($postedToken)) { // Process form } else { // Handling for invalid token } } // Generate a token for the displayed form $token = getToken(); ?> <form method="post"> <fieldset> <input type="hidden" name="token" value="<?php echo $token; ?>"> <!-- Add form content --> </fieldset> </form>
Additional Considerations:
By implementing this token-based solution, PHP developers can effectively prevent multiple form submissions, ensuring data integrity and enhancing user experience.
The above is the detailed content of How to Prevent Multiple Click Form Submission in PHP Using Unique Tokens?. For more information, please follow other related articles on the PHP Chinese website!