Is it recommended to use hidden input fields or headers to transmit CSRF tokens in PHP forms for better security?

To prevent CSRF attacks in PHP forms, it is recommended to use hidden input fields to transmit CSRF tokens rather than headers. This is because hidden input fields are included in the form submission data, making it easier to validate the token on the server side before processing the form. Using headers to transmit CSRF tokens can be less secure as they may not always be included in the request data.

<?php
session_start();

// Generate CSRF token
if (!isset($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

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

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