How can CSRF (Cross Site Request Forgery) attacks be prevented in PHP forms, and what role do session management and unique tokens play in this defense?

CSRF attacks can be prevented in PHP forms by using session management and generating unique tokens for each form submission. Session management helps to verify the user's identity, while unique tokens ensure that the form submission is legitimate and not initiated by a malicious third party.

<?php
session_start();

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

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

// Validate the token on form submission
if(isset($_POST['csrf_token']) && $_POST['csrf_token'] === $_SESSION['csrf_token']) {
    // Process the form data
} else {
    // Handle invalid token
    echo 'CSRF token validation failed';
}
?>