How can multiple form submissions be prevented in PHP?
To prevent multiple form submissions in PHP, you can use a token-based approach. Generate a unique token when the form is loaded, store it in a session variable, and include it as a hidden field in the form. Upon form submission, check if the token matches the one stored in the session. If they match, process the form data and regenerate a new token to prevent duplicate submissions.
<?php
session_start();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if ($_POST["token"] == $_SESSION["token"]) {
// Process form data
// Generate new token
$_SESSION["token"] = uniqid();
}
}
// Generate token and store it in session
$_SESSION["token"] = uniqid();
?>
<form method="post">
<input type="hidden" name="token" value="<?php echo $_SESSION["token"]; ?>">
<!-- Other form fields -->
<button type="submit">Submit</button>
</form>
Keywords
Related Questions
- How can the enctype attribute in the form tag affect file uploads in PHP?
- How can conditional statements affect the processing of form data in PHP scripts, and what precautions should be taken to ensure proper execution?
- Are there alternative methods to set the content of a field in Word using PHP, besides the shown approach?