Retrieving IP address

The best way to retrieve the current IP address of the client is via middleware usinga component such as ip-address-middleware.

This component can be installed via composer:

  1. composer require akrabat/ip-address-middleware

To use it, register the middleware with the App, providing a listof trusted proxies (e.g. varnish servers) if you are using them.:

  1. $checkProxyHeaders = true;
  2. $trustedProxies = ['10.0.0.1', '10.0.0.2'];
  3. $app->add(new RKA\Middleware\IpAddress($checkProxyHeaders, $trustedProxies));
  4. $app->get('/', function ($request, $response, $args) {
  5. $ipAddress = $request->getAttribute('ip_address');
  6. return $response;
  7. });

The middleware stores the client’s IP address in a request attribute, so accessis via $request->getAttribute('ip_address').