middlewares / client-ip
中间件用于检测客户端IP并将其保存为请求属性
v2.0.1
2020-12-02 00:05 UTC
Requires
- php: ^7.2 || ^8.0
- psr/http-server-middleware: ^1.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^2.0
- laminas/laminas-diactoros: ^2.2
- middlewares/utils: ^3.1
- oscarotero/php-cs-fixer-config: ^1.0
- phpstan/phpstan: ^0.12
- phpunit/phpunit: ^8|^9
- squizlabs/php_codesniffer: ^3.0
README
中间件用于检测客户端IP并将其保存为请求属性。
需求
- PHP >= 7.2
- 一个PSR-7 http库
- 一个PSR-15中间件分发器
安装
此包可以通过Composer安装和自动加载,名称为middlewares/client-ip。
composer require middlewares/client-ip
用法
$dispatcher = new Dispatcher([ new Middlewares\ClientIp(), function ($request) { //Get the client ip $ip = $request->getAttribute('client-ip'); } ]); $response = $dispatcher->dispatch(new ServerRequest());
代理
此选项配置通过代理进行检测。第一个参数是信任的代理IP列表或CIDR。如果为空,则不进行IP过滤。第二个参数是要检查的头信息列表。如果没有定义,则使用默认值['Forwarded', 'Forwarded-For', 'Client-Ip', 'X-Forwarded', 'X-Forwarded-For', 'X-Cluster-Client-Ip']
。默认禁用。
//Use proxies $middleware = (new Middlewares\ClientIp())->proxy(); //Trust only some proxies by ip $middleware = (new Middlewares\ClientIp())->proxy(['10.10.10.10', '10.10.10.11']); //Trust only some proxies by ip using a specific header $middleware = (new Middlewares\ClientIp())->proxy(['10.10.10.10', '10.10.10.11'], ['X-Forwarded-For']); // Trust only some proxies by cidr range // usefull when you have an autoscaled proxy(like haproxy) in a subnet $middleware = (new Middlewares\ClientIp())->proxy(['192.168.0.0/16', '10.0.0.0/8']);
属性
默认情况下,IP存储在服务器请求的client-ip
属性中。此选项允许修改这一点
//Save the ip in the "ip" attribute $middleware = (new Middlewares\ClientIp())->attribute('ip');
有关最近更改的更多信息,请参阅CHANGELOG,有关贡献详情,请参阅CONTRIBUTING。
MIT许可证(MIT)。有关更多信息,请参阅LICENSE。