Home >Web Front-end >JS Tutorial >How Can I Properly Configure CORS Headers in PHP to Avoid Cross-Origin Request Errors?
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.
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
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!"; }
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:
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!