Home >Backend Development >PHP Tutorial >Why is my CORS implementation not working in PHP?
CORS Not Functioning in PHP: A Resolved Case
Implementing Cross-Origin Resource Sharing (CORS) to facilitate data exchange across different origins is a common challenge. However, encountering CORS-related errors can be frustrating.
A user recently reported facing issues with CORS while attempting to submit form data from www.siteone.com to www.sitetwo.com. Despite implementing the required header settings in the "cors.php" file on the target domain, the user received "Access-control-Allow-Origin" errors.
Analysis and Solution:
Upon examining the code and headers, it was discovered that the initial implementation of CORS headers was incomplete. The following code snippet used in "cors.php" was not sufficient:
<code class="php">header('Access-Control-Allow-Origin: *'); header('Access-Control-Allow-Methods: POST, GET, OPTIONS');</code>
To handle CORS requests comprehensively, a more detailed response is necessary. The following updated code provided a valid solution:
<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>
Conclusion:
The CORS implementation error was resolved by incorporating the additional code lines that allowed requests from any origin, enabled credentials, and set a cache duration. This enhanced CORS handling ensured successful cross-origin data exchange.
The above is the detailed content of Why is my CORS implementation not working in PHP?. For more information, please follow other related articles on the PHP Chinese website!