What are some best practices for handling form submissions in PHP to prevent duplicate submissions and ensure data integrity?

To prevent duplicate form submissions and ensure data integrity in PHP, one best practice is to use a token-based approach. This involves generating a unique token for each form submission and validating it before processing the data. Additionally, you can disable form resubmission by redirecting the user to a different page after the form is successfully submitted.

// Generate a unique token for the form submission
$token = md5(uniqid(rand(), true));

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

// Check if the token is valid before processing the form data
if(isset($_POST['submit']) && $_POST['form_token'] === $_SESSION['form_token']) {
    // Process the form data
    // Clear the token to prevent duplicate submissions
    unset($_SESSION['form_token']);
    
    // Redirect the user to a different page
    header('Location: success.php');
    exit;
}