effectra/cors

PHP 库,用于在 HTTP 请求/响应中启用 CORS(跨源资源共享)。它遵循 PSR 指南,可以轻松集成到 PHP 项目中。

v1.0.0 2024-01-05 14:22 UTC

This package is auto-updated.

Last update: 2024-09-06 23:16:03 UTC


README

Effectra/cors 是一个 PHP 包,提供了处理 Web 应用程序中跨源资源共享 (CORS) 的中间件和服务类。CORS 是由 Web 浏览器实现的一种安全特性,用于控制对不同源资源的访问。

安装

您可以通过 Composer 安装 Effectra/cors 包

composer require effectra/cors

使用方法

CorsMiddleware

CorsMiddleware 类是一个 PSR-15 中间件,可用于中间件堆栈以处理 CORS 请求。它检查传入请求的 CORS 相关头,并将适当的头添加到响应中。

示例

use Effectra\Cors\CorsMiddleware;
use Effectra\Cors\CorsService;
use Psr\Http\Server\MiddlewareInterface;

// Create a CorsService instance with desired configuration
$corsService = new CorsService([
    'allowedOrigins' => ['https://example.com'],
    'allowedMethods' => ['GET', 'POST'],
    'allowedHeaders' => ['Content-Type'],
]);

// Create the CorsMiddleware instance
$corsMiddleware = new CorsMiddleware($corsService, ['/api']);

// Add the middleware to your middleware stack
$middlewareStack = [
    // Other middleware...
    $corsMiddleware,
    // Other middleware...
];

CorsService

CorsService 类提供了处理 CORS 请求的核心功能。它允许您配置各种 CORS 相关设置。

示例

use Effectra\Cors\CorsService;

// Create a CorsService instance with desired configuration
$corsService = new CorsService([
    'allowedOrigins' => ['https://example.com'],
    'allowedMethods' => ['GET', 'POST'],
    'allowedHeaders' => ['Content-Type'],
]);

// Check if a request is a CORS request
$isCorsRequest = $corsService->isCorsRequest($request);

// Check if a request is a preflight request
$isPreflightRequest = $corsService->isPreflightRequest($request);

// Handle a preflight request and add necessary headers to the response
$preflightResponse = $corsService->handlePreflightRequest($request);

// Check if a specific origin is allowed
$isOriginAllowed = $corsService->isOriginAllowed($request);

// Add CORS headers to the actual response
$actualResponse = $corsService->addActualRequestHeaders($response, $request);

配置

CorsService 类允许您使用选项数组配置各种 CORS 相关设置。

可用选项

  • allowedOrigins:允许的源数组。
  • allowedOriginsPatterns:允许的源模式数组(通配符)。
  • allowedMethods:允许的 HTTP 方法数组。
  • allowedHeaders:允许的头数组。
  • supportsCredentials:是否支持凭据(cookies、HTTP 认证)。
  • maxAge:预检请求结果可缓存的最高时间(以秒为单位)。
  • exposedHeaders:暴露给响应的头数组。

贡献

如果您想为此项目做出贡献,请遵循我们的 贡献指南

许可证

Effectra/cors 包是开源软件,采用 MIT 许可证