What potential issues arise when generating a new CSRF code on each page load in PHP?

Generating a new CSRF code on each page load in PHP can lead to validation failures if the user submits a form with an older CSRF code. To solve this issue, the CSRF code should be generated once per session and stored in a session variable for validation.

// Start or resume a session
session_start();

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

// Use $_SESSION['csrf_token'] in forms for CSRF validation