What are the best practices for handling sessions and tokens in PHP when dealing with iframes and cross-origin requests?

When dealing with iframes and cross-origin requests in PHP, it is important to handle sessions and tokens securely to prevent unauthorized access to sensitive data. One way to achieve this is by using CSRF tokens to validate requests and ensuring that session data is properly managed and protected.

// Start session
session_start();

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

// Validate CSRF token
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
        // Invalid CSRF token
        exit('Invalid CSRF token');
    }
}

// Set CSRF token in form
echo '<input type="hidden" name="csrf_token" value="' . $_SESSION['csrf_token'] . '">';

// Handle cross-origin requests
header("Access-Control-Allow-Origin: https://example.com");
header("Access-Control-Allow-Credentials: true");