Configuring CORS in .htaccess vs. PHP
When developing a cross-origin application using Angular.js, it is necessary to enable CORS (Cross-Origin Resource Sharing) to allow requests from different origins. While .htaccess is a common method for configuring CORS, sometimes it may not work as expected.
According to the user's .htaccess configuration, the following headers should be added:
Header set Access-Control-Allow-Origin "*" Header set Access-Control-Allow-Methods: "GET,POST,OPTIONS,DELETE,PUT"
However, the Angular application is still encountering an error. As the .htaccess configuration for static files is already in place, the user decides to explore an alternative approach using PHP.
In the index.php file, the following code is added:
<code class="php">// Allow from any origin if (isset($_SERVER['HTTP_ORIGIN'])) { // should do a check here to match $_SERVER['HTTP_ORIGIN'] to a // whitelist of safe domains 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, PUT, DELETE, OPTIONS"); if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}"); }</code>
Since Slim is the framework being used, an additional route is added to handle OPTIONS requests:
<code class="php">// return HTTP 200 for HTTP OPTIONS requests $app->map('/:x+', function($x) { http_response_code(200); })->via('OPTIONS');</code>
By implementing CORS configuration in PHP instead of .htaccess, the user successfully resolves the cross-origin request issue and the Angular application can now make requests to the RESTful service.
The above is the detailed content of Why Choose PHP Over .htaccess for CORS Configuration?. For more information, please follow other related articles on the PHP Chinese website!