How can developers implement a one-time token system in PHP to prevent multiple submissions or unauthorized access to restricted pages?

To implement a one-time token system in PHP, developers can generate a unique token for each form submission or page access. This token is then validated and marked as used to prevent multiple submissions or unauthorized access. By checking the validity of the token before processing the form data or allowing access to restricted pages, developers can ensure that each token is only used once.

<?php
session_start();

// Generate a unique token
$token = bin2hex(random_bytes(16));

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

// Include this token in the form or link
echo "<form action='process_form.php' method='post'>";
echo "<input type='hidden' name='token' value='$token'>";
echo "<input type='text' name='data'>";
echo "<input type='submit' value='Submit'>";
echo "</form>";

// Validate the token before processing the form data
if(isset($_POST['token']) && $_POST['token'] == $_SESSION['token']) {
    // Process the form data
    // Mark the token as used
    unset($_SESSION['token']);
} else {
    // Handle unauthorized access
    echo "Unauthorized access!";
}
?>