middlewares / client-ip
Middleware to detect the client ip and save it as a request attribute
Installs: 495 439
Dependents: 10
Suggesters: 0
Security: 0
Stars: 16
Watchers: 4
Forks: 6
Open Issues: 0
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
Middleware to detect the client ip and save it as a request attribute.
Requirements
- PHP >= 7.2
- A PSR-7 http library
- A PSR-15 middleware dispatcher
Installation
This package is installable and autoloadable via Composer as middlewares/client-ip.
composer require middlewares/client-ip
Usage
$dispatcher = new Dispatcher([ new Middlewares\ClientIp(), function ($request) { //Get the client ip $ip = $request->getAttribute('client-ip'); } ]); $response = $dispatcher->dispatch(new ServerRequest());
proxy
This option configures the detection through proxies. The first argument is an array of ips or cidr of the trusted proxies. If it's empty, no ip filtering is made. The second argument is a list of the headers to inspect. If it's not defined, uses the default value ['Forwarded', 'Forwarded-For', 'Client-Ip', 'X-Forwarded', 'X-Forwarded-For', 'X-Cluster-Client-Ip']
. Disabled by default.
//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']);
attribute
By default, the ip is stored in the client-ip
attribute of the server request. This options allows to modify that:
//Save the ip in the "ip" attribute $middleware = (new Middlewares\ClientIp())->attribute('ip');
Please see CHANGELOG for more information about recent changes and CONTRIBUTING for contributing details.
The MIT License (MIT). Please see LICENSE for more information.