Home >Web Front-end >JS Tutorial >How Can I Properly Configure CORS Headers in PHP to Avoid Cross-Origin Request Errors?

How Can I Properly Configure CORS Headers in PHP to Avoid Cross-Origin Request Errors?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-16 06:15:16250browse

How Can I Properly Configure CORS Headers in PHP to Avoid Cross-Origin Request Errors?

Cross-Origin Request Headers (CORS) with PHP Headers

Understanding CORS

Cross-Origin Request Sharing (CORS) is a mechanism that allows browsers to safely make cross-origin HTTP requests, enabling communication between different domains or subdomains. This mechanism helps prevent unauthorized access to resources, ensuring data privacy and security.

CORS Flow with Example Headers

To demonstrate the CORS flow, let's consider a simplified PHP script:

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: *");

This script allows cross-origin requests from any origin and any header. However, in certain cases, you may encounter an error message like:

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

Addressing the Error

To correctly handle CORS requests, you need to specify the allowed headers explicitly. A more comprehensive function that responds properly to CORS requests is:

function cors() {
    if (isset($_SERVER['HTTP_ORIGIN'])) {
        header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
        header('Access-Control-Allow-Credentials: true');
        header('Access-Control-Max-Age: 86400');
    }

    if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'])) {
            header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
        }
        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) {
            header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
        }
        exit(0);
    }

    echo "You have CORS!";
}

Security Notes

1. Validate the HTTP_ORIGIN:
When you receive an HTTP_ORIGIN header, always check it against a whitelist of approved origins before allowing the request.

2. X-Requested-With Validation:
The script above allows any header, including X-Requested-With. This should be validated as well, especially in a production environment.

3. Read the CORS Spec:
For a comprehensive understanding of CORS, refer to the official specifications:

  • [HTTP Access Control](https://developer.mozilla.org/en/HTTP_access_control)
  • [Fetch Standard](https://fetch.spec.whatwg.org/#http-cors-protocol)

TL;DR

  • CORS enables cross-origin HTTP requests by modifying the browser's security policy.
  • When responding to CORS requests, you must set the Access-Control-Allow-Origin header.
  • Specify the allowed headers explicitly using Access-Control-Allow-Headers.
  • Always validate the HTTP_ORIGIN and other relevant headers for security reasons.

The above is the detailed content of How Can I Properly Configure CORS Headers in PHP to Avoid Cross-Origin Request Errors?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn