Home >Backend Development >PHP Tutorial >Why is my CORS Request Failing with \'Origin is not allowed by Access-Control-Allow-Origin\'?
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.
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');
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>
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!