Home > Backend Development > PHP Tutorial > How to Enable CORS Using .htaccess or PHPCORS?

How to Enable CORS Using .htaccess or PHPCORS?

Barbara Streisand
Release: 2024-10-31 19:17:02
Original
1001 people have browsed it

How to Enable CORS Using .htaccess or PHPCORS?

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"
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template