Comprehensive Guide to CORS Cross-Origin Request Headers Configuration in PHP

Nov 10, 2025 · Programming · 14 views · 7.8

Keywords: CORS | PHP | Cross-Origin Requests | Access-Control-Allow-Headers | Preflight Requests

Abstract: This technical article provides an in-depth analysis of CORS implementation in PHP, focusing on the limitations of wildcard usage in Access-Control-Allow-Headers configuration. It explains preflight request mechanisms, offers complete PHP implementation solutions, and addresses common CORS errors with practical examples. The article covers security considerations and best practices for proper cross-origin request handling.

Fundamental Principles of CORS Cross-Origin Requests

Cross-Origin Resource Sharing (CORS) is the core mechanism for handling cross-origin requests in modern web development. When browsers detect JavaScript code attempting to access resources from different origins, they automatically enforce same-origin policy restrictions. CORS uses specific HTTP headers to inform browsers whether cross-origin access is permitted.

A common error encountered when configuring CORS in PHP environments is:

Request header field X-Requested-With is not allowed by Access-Control-Allow-Headers

The root cause of this error lies in misunderstanding the conditions for using the wildcard * in the Access-Control-Allow-Headers header.

Access-Control-Allow-Headers Wildcard Limitations

According to the latest CORS specification, Access-Control-Allow-Headers: * is only effective under specific conditions. When requests do not include credentials (such as Cookies or HTTP authentication), the wildcard * has special meaning, indicating that all request headers are allowed. However, in requests with credentials, * is treated as a literal header name rather than a wildcard.

It is particularly important to note that the Authorization header can never be wildcarded and must always be explicitly listed. This is why using wildcards in requests containing custom headers like X-Requested-With causes preflight request failures.

Detailed Preflight Request Mechanism

When browsers detect non-simple requests, they first send OPTIONS method preflight requests. Preflight requests contain two critical headers:

Access-Control-Request-Method: POST
Access-Control-Request-Headers: X-Requested-With, Content-Type

Servers must properly respond to these preflight requests, explicitly indicating allowed methods and headers. Below is a complete PHP CORS handling function:

<?php
function handleCORS() {
    // Handle preflight requests
    if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
        header('Access-Control-Allow-Origin: https://example.com');
        header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
        header('Access-Control-Allow-Headers: X-Requested-With, Content-Type, Authorization');
        header('Access-Control-Max-Age: 86400');
        exit(0);
    }
    
    // Handle actual requests
    header('Access-Control-Allow-Origin: https://example.com');
    header('Access-Control-Allow-Credentials: true');
}
?>

Security Configuration Best Practices

In production environments, it is strongly recommended to avoid using Access-Control-Allow-Origin: *. Instead, dynamically set allowed origins based on $_SERVER['HTTP_ORIGIN'] or maintain a whitelist of trusted origins.

For requests containing credentials, explicitly specify the list of allowed headers:

header('Access-Control-Allow-Headers: X-Requested-With, Content-Type, Accept, Authorization');

This explicit configuration not only follows security best practices but also avoids CORS errors caused by browser compatibility issues.

Common Problem Solutions

The correct solution for the "X-Requested-With header not allowed" error is:

<?php
header('Access-Control-Allow-Origin: https://yourdomain.com');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: X-Requested-With, Content-Type');
header('Access-Control-Allow-Credentials: true');
?>

This configuration ensures that the X-Requested-With header is explicitly allowed in preflight requests, thereby avoiding CORS errors.

Caching and Performance Optimization

By setting the Access-Control-Max-Age header, the frequency of preflight requests can be significantly reduced. For example, setting it to 86400 seconds (24 hours) means browsers won't send repeated preflight requests for the same URL within 24 hours.

However, it's important to note that excessively long cache times may introduce risks when security policies change. It's recommended to balance cache duration based on actual security requirements.

Browser Compatibility Considerations

While modern browsers support the CORS protocol, differences still exist in handling preflight requests after redirects. Some browser versions do not allow cross-origin redirects to follow preflight requests. In such cases, it's advisable to avoid unnecessary redirects on the server side or adjust requests to make them simple requests.

By deeply understanding the CORS protocol specification and properly configuring PHP headers, developers can effectively resolve various issues in cross-origin requests and build secure, reliable web applications.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.