hkvstore/cors-middleware
Composer 安装命令:
composer require hkvstore/cors-middleware
包简介
PSR-7 and PSR-15 CORS middleware
关键字:
README 文档
README
This middleware implements Cross-origin resource sharing. It supports both PSR-7 style doublepass and PSR-15 middleware standards. It has been tested with Slim Framework and Zend Expressive. Internally the middleware uses neomerx/cors-psr7 library for heavy lifting.
Install
Install using composer.
$ composer require tuupola/cors-middleware
Usage
Documentation assumes you have working knowledge of CORS. There are no mandatory parameters. If you are using Zend Expressive skeleton middlewares are added to file called config/pipeline.php. Note that you must disable the default ImplicitOptionsMiddleware for this middleware to work.
use Tuupola\Middleware\CorsMiddleware; #$app->pipe(ImplicitOptionsMiddleware::class); $app->pipe(CorsMiddleware::class);
Slim Framework does not have specified config files. Otherwise adding the middleware is similar with previous.
$app->add(new Tuupola\Middleware\CorsMiddleware);
Rest of the examples use Slim Framework.
If called without any parameters the following defaults are used.
$app->add(new Tuupola\Middleware\CorsMiddleware([ "origin" => ["*"], "methods" => ["GET", "POST", "PUT", "PATCH", "DELETE"], "headers.allow" => [], "headers.expose" => [], "credentials" => false, "cache" => 0, ]));
$ curl "https://api.example.com/" \ --request OPTIONS \ --include --header "Access-Control-Request-Method: PUT" \ --header "Origin: http://www.example.com" HTTP/1.1 200 OK Access-Control-Allow-Origin: http://www.example.com Vary: Origin Access-Control-Allow-Methods: GET, POST, PUT, PATCH, DELETE
However, you most likely want to change some of the defaults. For example if developing a REST API which supports caching and conditional requests you could use the following.
$app->add(new Tuupola\Middleware\CorsMiddleware([ "origin" => ["*"], "methods" => ["GET", "POST", "PUT", "PATCH", "DELETE"], "headers.allow" => ["Authorization", "If-Match", "If-Unmodified-Since"], "headers.expose" => ["Etag"], "credentials" => true, "cache" => 86400 ]));
$ curl "https://api.example.com/foo" \ --request OPTIONS \ --include \ --header "Origin: http://www.example.com" \ --header "Access-Control-Request-Method: PUT" \ --header "Access-Control-Request-Headers: Authorization, If-Match" HTTP/1.1 200 OK Access-Control-Allow-Origin: http://www.example.com Access-Control-Allow-Credentials: true Vary: Origin Access-Control-Max-Age: 86400 Access-Control-Allow-Methods: GET, POST, PUT, PATCH, DELETE Access-Control-Allow-Headers: authorization, if-match, if-unmodified-since
$ curl "https://api.example.com/foo" \ --request PUT \ --include \ --header "Origin: http://www.example.com" HTTP/1.1 200 OK Access-Control-Allow-Origin: http://www.example.com Access-Control-Allow-Credentials: true Vary: Origin Access-Control-Expose-Headers: Etag
Parameters
Origin
By default all origins are allowed. You can limit allowed origins by passing them as an array.
$app->add(new Tuupola\Middleware\CorsMiddleware([ "origin" => ["app-1.example.com", "app-2.example.com"] ]));
You can also use wildcards to define multiple origins at once. Wildcards are matched by using the fnmatch() function.
$app->add(new Tuupola\Middleware\CorsMiddleware([ "origin" => ["*.example.com"] ]));
Methods
Methods can be passed either as an array or a callable which returns an array. Below example is for Zend Expressive where value of methods is dynamic depending on the requested route.
use Tuupola\Middleware\CorsMiddleware; use Zend\Expressive\Router\RouteResult; $app->pipe(new CorsMiddleware([ "origin" => ["*"], "methods" => function($request) { $result = $request->getAttribute(RouteResult::class); $route = $result->getMatchedRoute(); return $route->getAllowedMethods(); } ]));
Same thing for Slim 3. This assumes you have not defined the OPTIONS route.
use Fastroute\Dispatcher; use Tuupola\Middleware\CorsMiddleware; $app->add( new CorsMiddleware([ "origin" => ["*"], "methods" => function($request) use ($app) { $container = $app->getContainer(); $dispatch = $container["router"]->dispatch($request); if (Dispatcher::METHOD_NOT_ALLOWED === $dispatch[0]) { return $dispatch[1]; } } ]) );
Logger
The optional logger parameter allows you to pass in a PSR-3 compatible logger to help with debugging or other application logging needs.
$logger = Monolog\Logger("slim"); $rotating = new RotatingFileHandler(__DIR__ . "/logs/slim.log", 0, Logger::DEBUG); $logger->pushHandler($rotating); $app->add(new Tuupola\Middleware\CorsMiddleware([ "logger" => $logger, ]));
Error
Error is called when CORS request fails. It receives last error message in arguments. This can be used for example to create application/json responses when CORS request fails.
$app->add(new Tuupola\Middleware\CorsMiddleware([ "methods" => ["GET", "POST", "PUT"], "error" => function ($request, $response, $arguments) { $data["status"] = "error"; $data["message"] = $arguments["message"]; return $response ->withHeader("Content-Type", "application/json") ->write(json_encode($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT)); } ]));
$ curl https://api.example.com/foo \
--request OPTIONS \
--include \
--header "Access-Control-Request-Method: PATCH" \
--header "Origin: http://www.example.com"
HTTP/1.1 401 Unauthorized
Content-Type: application/json
Content-Length: 83
{
"status": "error",
"message": "CORS requested method is not supported."
}
Server origin
If your same-origin requests contain an unnecessary Origin header, they might get blocked in case the server origin is not among the allowed origins already. In this case you can use the optional origin.server parameter to specify the origin of the server.
$app->add(new Tuupola\Middleware\CorsMiddleware([ "origin.server" => "https://example.com" ]));
$ curl https://example.com/api \
--request POST \
--include \
--header "Origin: https://example.com"
HTTP/1.1 200 OK
Testing
You can run tests either manually or automatically on every code change. Automatic tests require entr to work.
$ make test
$ brew install entr $ make watch
Contributing
Please see CONTRIBUTING for details.
Security
If you discover any security related issues, please email tuupola@appelsiini.net instead of using the issue tracker.
License
The MIT License (MIT). Please see License File for more information.
hkvstore/cors-middleware 适用场景与选型建议
hkvstore/cors-middleware 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 8.13k 次下载、GitHub Stars 达 0, 最近一次更新时间为 2025 年 02 月 02 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「cors」 「middleware」 「psr-7」 「psr-15」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 hkvstore/cors-middleware 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 hkvstore/cors-middleware 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 hkvstore/cors-middleware 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Shoot aims to make providing data to your templates more manageable
Model of a web-based resource
Interfaces for web resource models and services to retrieve and create them
Interface for a factory to create Psr\Http\Message\StreamInterface objects
A PSR-7 compatible library for making CRUD API endpoints
Retrieve a WebResourceInterface instance over HTTP
统计信息
- 总下载量: 8.13k
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 4
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2025-02-02