What is the purpose of using a Form Token in PHP and how does it help prevent CSRF attacks?

CSRF attacks occur when a malicious website tricks a user's browser into making unintended requests to a different website where the user is authenticated. One way to prevent CSRF attacks is by using a Form Token in PHP. This involves generating a unique token for each form submission and verifying it on the server side to ensure that the request is legitimate.

<?php
session_start();

// Generate a random token and store it in the session
if (!isset($_SESSION['token'])) {
    $_SESSION['token'] = bin2hex(random_bytes(32));
}

// Add the token to the form
echo '<form method="post">';
echo '<input type="hidden" name="token" value="' . $_SESSION['token'] . '">';
echo '<input type="submit" value="Submit">';
echo '</form>';

// Verify the token on form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!isset($_POST['token']) || $_POST['token'] !== $_SESSION['token']) {
        die('CSRF token validation failed.');
    } else {
        // Process the form data
    }
}
?>