How can tokens be used to verify that a form was submitted from the correct source in PHP?

To verify that a form was submitted from the correct source in PHP, you can use tokens. Tokens are unique values generated on the server side and included in the form as hidden fields. When the form is submitted, the token is validated to ensure that it matches the one generated on the server side, thus verifying the source of the form submission.

<?php
session_start();

// Generate a token
$token = bin2hex(random_bytes(32));
$_SESSION['token'] = $token;

// Include the token in the form
echo '<form method="post">';
echo '<input type="hidden" name="token" value="' . $token . '">';
// Add other form fields here
echo '</form>';

// Validate the token on form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['token']) && $_POST['token'] === $_SESSION['token']) {
        // Token is valid, process the form
    } else {
        // Token is not valid, handle the error
    }
}
?>