Home  >  Article  >  Backend Development  >  Why Is CORS Not Working in My PHP Application?

Why Is CORS Not Working in My PHP Application?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-03 04:54:02189browse

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:

<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>

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.

The above is the detailed content of Why Is CORS Not Working in My PHP Application?. 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