How can PHP developers effectively implement CSRF protection in their web applications?

Cross-Site Request Forgery (CSRF) attacks occur when a malicious website tricks a user's browser into making a request to a different website where the user is authenticated. To prevent CSRF attacks, PHP developers can implement CSRF protection by generating a unique token for each user session and including it in forms. Upon form submission, the server verifies that the token matches the one stored in the session.

<?php
session_start();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        die('CSRF token validation failed.');
    }
    
    // Process form data here
}

$csrf_token = bin2hex(random_bytes(32));
$_SESSION['csrf_token'] = $csrf_token;
?>

<form method="post">
    <input type="hidden" name="csrf_token" value="<?php echo $csrf_token; ?>">
    <!-- Other form fields here -->
    <button type="submit">Submit</button>
</form>