Home  >  Article  >  Backend Development  >  Why is CORS not working in my PHP application despite setting Access-Control-Allow-Origin headers?

Why is CORS not working in my PHP application despite setting Access-Control-Allow-Origin headers?

DDD
DDDOriginal
2024-11-03 04:55:02355browse

Why is CORS not working in my PHP application despite setting Access-Control-Allow-Origin headers?

CORS not working in PHP

When attempting to send a POST request with form data from www.siteone.com to www.sitetwo.com using CORS, 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.

Despite configuring the CORS headers in cors.php on www.sitetwo.com:

<code class="php">header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');</code>

The request is still failing due to an improper implementation of the header configuration. The updated code that addresses this issue is:

<code class="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);
}

echo "You have CORS!";</code>

This revised code responds to the Access-Control headers received during OPTIONS requests and allows requests from any origin, allowing CORS to function properly.

The above is the detailed content of Why is CORS not working in my PHP application despite setting Access-Control-Allow-Origin headers?. 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