What are the best practices for generating and validating CSRF tokens in PHP?

CSRF tokens are used to protect against Cross-Site Request Forgery attacks by ensuring that a request comes from a legitimate source. To generate a CSRF token in PHP, you can use functions like bin2hex() to create a random token and store it in a session variable. When a form is submitted, compare the token in the form with the one stored in the session to validate it.

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

// Include this token in your form
<input type="hidden" name="csrf_token" value="<?php echo $token; ?>">

// Validate CSRF token
if ($_POST['csrf_token'] !== $_SESSION['csrf_token']) {
    // Token mismatch, handle error
} else {
    // Token is valid, proceed with form submission
}