Home  >  Article  >  Backend Development  >  How to Enable CORS for Slim PHP Framework Using PHP Headers?

How to Enable CORS for Slim PHP Framework Using PHP Headers?

Susan Sarandon
Susan SarandonOriginal
2024-11-01 04:40:02788browse

How to Enable CORS for Slim PHP Framework Using PHP Headers?

Enabling CORS for Slim PHP Framework in .htaccess

To enable Cross-Origin Resource Sharing (CORS) for a RESTful service created with the SLIM PHP framework, modifications to the .htaccess file are commonly used. However, if issues persist after making the recommended change in .htaccess, an alternative approach can be employed.

Using PHP Headers

Instead of setting CORS headers in .htaccess, it can be done directly in the PHP code, specifically in the index.php file. By adding the following code to the beginning of the file, CORS headers will be set for every HTTP request received by the application:

<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>

Handling OPTIONS Requests

If using the SLIM PHP framework, you may also need to handle OPTIONS requests. Add the following route to the $app object to ensure OPTIONS requests receive a HTTP 200 response:

<code class="php">// return HTTP 200 for HTTP OPTIONS requests
$app->map('/:x+', function($x) {
    http_response_code(200);
})->via('OPTIONS');</code>

These PHP modifications provide an alternative to setting CORS headers in .htaccess. By adding both code blocks to the index.php file, you can enable CORS for your SLIM PHP RESTful service.

The above is the detailed content of How to Enable CORS for Slim PHP Framework Using PHP Headers?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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