How can the Origin header protection (CSRF protection) be implemented in PHP scripts to enhance security?

Origin header protection (CSRF protection) can be implemented in PHP scripts by checking the `Origin` header of incoming requests and verifying that it matches an expected value. This helps prevent cross-site request forgery attacks by ensuring that the request originates from an allowed domain.

// Check if the Origin header is present in the request
if(isset($_SERVER['HTTP_ORIGIN'])){
    $allowedOrigins = array('http://example.com', 'https://example.com');
    $origin = $_SERVER['HTTP_ORIGIN'];
    
    // Verify that the Origin header matches an allowed value
    if(in_array($origin, $allowedOrigins)){
        header('Access-Control-Allow-Origin: ' . $origin);
    } else {
        // Handle unauthorized requests
        http_response_code(403);
        die('Unauthorized request');
    }
} else {
    // Handle requests without an Origin header
    http_response_code(400);
    die('Origin header missing');
}