camilord/php-cors

Symfony HttpFoundation 的跨源资源共享库

1.3.1 2024-08-09 02:54 UTC

This package is auto-updated.

Last update: 2024-09-09 03:06:15 UTC


README

Unit Tests PHPStan Level 9 Code Coverage Packagist License Latest Stable Version Total Downloads Fruitcake

这是一个库和中间件,可以为您使用 application 的 http-{foundation,kernel} 实现跨源资源共享。它尝试实现 W3C 建议 的跨源资源共享。

注意:这是 https://github.com/asm89/stack-cors 的独立分支,与 CorsService 的选项兼容。

安装

使用 composer 安装 fruitcake/php-cors

使用方法

此包可以作为库使用。您可以在框架中使用它

选项

allowedMethodsallowedHeaders 选项不区分大小写。

您不需要同时提供 allowedOriginsallowedOriginsPatterns。如果传入的字符串之一匹配,则被认为是有效的来源。允许 Origins 中的通配符将被转换为模式。

如果将 ['*'] 提供给 allowedMethodsallowedOriginsallowedHeaders,则允许所有方法/来源/标题。

注意:允许单个静态来源将提高缓存能力。

示例:使用库

<?php

use Fruitcake\Cors\CorsService;

$cors = new CorsService([
    'allowedHeaders'         => ['x-allowed-header', 'x-other-allowed-header'],
    'allowedMethods'         => ['DELETE', 'GET', 'POST', 'PUT'],
    'allowedOrigins'         => ['https://', 'https://*.example.com'],
    'allowedOriginsPatterns' => ['/localhost:\d/'],
    'exposedHeaders'         => ['Content-Encoding'],
    'maxAge'                 => 0,
    'supportsCredentials'    => false,
]);

$cors->addActualRequestHeaders(Response $response, $origin);
$cors->handlePreflightRequest(Request $request);
$cors->isActualRequestAllowed(Request $request);
$cors->isCorsRequest(Request $request);
$cors->isPreflightRequest(Request $request);

许可协议

在 MIT 许可证下发布,请参阅 LICENSE

此包自 2022 年从 https://github.com/asm89/stack-cors 分离出来,并作为独立库开发