How can tokens be used to prevent resubmission of form data in PHP?

To prevent resubmission of form data in PHP, tokens can be used. Tokens are unique identifiers generated for each form submission and stored in a session variable. When the form is submitted, the token is checked to ensure that the form data is not being resubmitted.

<?php
session_start();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!isset($_POST['token']) || $_POST['token'] !== $_SESSION['token']) {
        // Token mismatch, do not process the form
        die('Token mismatch. Please try submitting the form again.');
    }

    // Process the form data

    // Generate a new token for the next form submission
    $token = bin2hex(random_bytes(32));
    $_SESSION['token'] = $token;
} else {
    // Generate a token for the initial form load
    $token = bin2hex(random_bytes(32));
    $_SESSION['token'] = $token;
}
?>

<form method="post" action="">
    <input type="hidden" name="token" value="<?php echo $token; ?>">
    <!-- Other form fields -->
    <button type="submit">Submit</button>
</form>