How can the use of multiple tabs or browser sessions impact the effectiveness of CSRF protection mechanisms in PHP?

When multiple tabs or browser sessions are used, CSRF protection mechanisms in PHP can be compromised because each session may have its own CSRF token. To address this issue, the CSRF token should be stored in the session itself rather than in a hidden form field. This ensures that each session has its own unique CSRF token, preventing CSRF attacks across multiple tabs or sessions.

<?php
session_start();

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

function generate_csrf_token() {
    return $_SESSION['csrf_token'];
}

function validate_csrf_token($token) {
    return $token === $_SESSION['csrf_token'];
}
?>