What are the best practices for implementing a token-based system in PHP to prevent form resubmission?

To prevent form resubmission in PHP, a common practice is to implement a token-based system. This involves generating a unique token when the form is initially loaded, storing it in a session variable, and then checking for its presence and validity when the form is submitted. If the token is valid, the form submission is processed, and a new token is generated for subsequent requests.

<?php

session_start();

// Generate a unique token
$token = md5(uniqid(rand(), true));

// Store the token in a session variable
$_SESSION['token'] = $token;

// Display the token in the form
echo '<input type="hidden" name="token" value="' . $token . '">';

// Validate the token on form submission
if ($_POST['token'] === $_SESSION['token']) {
    // Process the form submission
    // Generate a new token for subsequent requests
    $_SESSION['token'] = md5(uniqid(rand(), true));
} else {
    // Token is invalid, handle accordingly
}

?>