Home > Backend Development > PHP Tutorial > Why is my CORS Request Failing with \'Origin is not allowed by Access-Control-Allow-Origin\'?

Why is my CORS Request Failing with \'Origin is not allowed by Access-Control-Allow-Origin\'?

Linda Hamilton
Release: 2024-11-03 09:54:29
Original
794 people have browsed it

Why is my CORS Request Failing with

CORS Not Functioning in PHP

Problem Description:

When attempting to transmit form data via CORS (Cross-Origin Resource Sharing) from www.siteone.com to www.sitetwo.com, the following error is encountered:

XMLHttpRequest cannot load http://www.sitetwo.com/cors.php. Origin http://www.siteone.com is not allowed by Access-Control-Allow-Origin.
Copy after login

Despite setting the following headers in cors.php on www.sitetwo.com:

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
Copy after login

Solution:

The problem lies in the way CORS request headers are handled. The following updated code for cors.php provides a more comprehensive response to CORS requests:

<code class="php"><?php
// Allow from any origin
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');    // cache for 1 day
}

// Access-Control headers are received during OPTIONS requests
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);
}

// Respond to the request
echo "You have CORS!";
?></code>
Copy after login

This revised code allows cross-origin requests from any origin, validates request methods and headers, caches the CORS response for a day, and responds appropriately to OPTIONS requests.

The above is the detailed content of Why is my CORS Request Failing with \'Origin is not allowed by Access-Control-Allow-Origin\'?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template