Home >Backend Development >PHP Tutorial >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!