Home > Article > Backend Development > How to Enable CORS for Cross-Origin Requests in .htaccess and PHP?
Allowing Cross-Origin Resource Sharing (CORS) in .htaccess
Implementing CORS using .htaccess can sometimes encounter issues. Although adding the line Header set Access-Control-Allow-Origin "*", as advised for Angular.js CORS support, may not resolve all errors.
Alternative Approach: Setting Headers in PHP
To address this, an alternative method is to set the headers in the PHP script itself. For example, if using the SLIM PHP framework, one can add the following to the index.php file:
<code class="php">// Allow CORS headers header('Access-Control-Allow-Origin: *'); header('Access-Control-Allow-Headers: Content-Type'); header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS'); // Return 200 for OPTIONS requests $app->map('/:x+', function ($x) { http_response_code(200); })->via('OPTIONS');</code>
This sets the Access-Control-Allow-Origin header to allow requests from any origin, enabling CORS for various HTTP methods.
Note: For added security, it is recommended to replace the wildcard * with a specific list of allowed origins.
The above is the detailed content of How to Enable CORS for Cross-Origin Requests in .htaccess and PHP?. For more information, please follow other related articles on the PHP Chinese website!