"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Why doesn't CORS work in my PHP application?

Why doesn't CORS work in my PHP application?

Posted on 2025-04-15
Browse:752

Why Is CORS Not Working in My PHP Application?

CORS Not Working in PHP

In cross-origin resource sharing (CORS), a web page can request resources from another origin, typically involving different domains, ports, or protocols. However, by default, browsers restrict such requests due to security concerns.

In the given scenario, the user is attempting a POST request from www.siteone.com to www.sitetwo.com using CORS. The error encountered suggests that there is a mismatch between the request and response headers.

To configure CORS properly, it's crucial to handle it carefully. The following PHP function provides a more comprehensive approach:

// 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!";

By replacing the original code with this enhanced function, the user successfully resolved the CORS issue. This approach ensures that all necessary headers are set appropriately, enabling cross-origin requests to work as intended.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3