How can server-side validation be used to prevent double submissions in PHP?

Server-side validation can prevent double submissions in PHP by generating a unique token when the form is loaded and storing it in a session variable. When the form is submitted, the server checks if the token in the form matches the one stored in the session. If they match, the form submission is processed, and the token is regenerated. If they don't match, the submission is rejected as a potential double submission.

session_start();

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (!isset($_POST['token']) || $_POST['token'] !== $_SESSION['token']) {
        // Handle potential double submission
        die('Double form submission detected');
    }

    // Process form submission

    // Regenerate token
    $_SESSION['token'] = uniqid();
}

// Generate token and store it in session
$_SESSION['token'] = uniqid();