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>