Enabling CORS Using .htaccess or PHP
CORS (Cross-Origin Resource Sharing) enables communication between web applications across different domains. To enable CORS using .htaccess, add the following lines:
Header set Access-Control-Allow-Origin "*" Header set Access-Control-Allow-Methods: "GET,POST,OPTIONS,DELETE,PUT"
However, if this doesn't work, an alternative method is to enable CORS in PHP through the index.php file:
<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 for OPTIONS requests if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') { header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS"); header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}"); }</code>
For Slim applications, add this route to handle OPTIONS requests:
<code class="php">$app->map('/:x+', function($x) { http_response_code(200); }) ->via('OPTIONS');</code>
This approach enables CORS by setting the necessary headers and responding appropriately to OPTIONS requests.
The above is the detailed content of How to Enable CORS Using .htaccess or PHPCORS?. For more information, please follow other related articles on the PHP Chinese website!