What is the purpose of generating a token in PHP for form submission?

Generating a token in PHP for form submission helps prevent CSRF (Cross-Site Request Forgery) attacks. By including a unique token in each form submission, the server can verify that the request is legitimate and not coming from a malicious source. This helps protect sensitive data and prevent unauthorized actions on the website.

// Generate a unique token and store it in a session variable
$token = bin2hex(random_bytes(32));
$_SESSION['csrf_token'] = $token;

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

// Validate the token on form submission
if ($_POST['csrf_token'] !== $_SESSION['csrf_token']) {
    // Token mismatch, handle error
    die('CSRF Token validation failed');
} else {
    // Token is valid, process the form submission
}