Search code examples
phpslimslim-3

Retrieving IP address in SlimFramework 3 with rka-ip-address-middleware


Background

I am creating a REST API to work with my mobile app. It is important that I keep a record of any request made to the server by IP address for legality purposes.

I understand people can spoof the IP if they want, but that is not a concern. There is an API key for security, this is simply a CYA precaution.

Using the middleware Slim 3 suggest here the value is always NULL I am testing this from my localhost (If that makes a difference, but I do not know why it would).

Problem

When I hit the get request endpoint and I try to capture the IP it is always NULL.

Example

use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;

require '../vendor/autoload.php';

    $app->get('/api/v1/customer', function (Request $request, Response $response) {
        $requestIP = $request->getAttribute('ip_address');
         var_dump($requestIP);
         echo $requestIP;
         echo 'CUSOTMERS!';

        return $response;
    });

$app->run();

Output

NULL CUSOTMERS!

Question

What is the proper way to capture the IP address from the request using this rka-ip-address-middleware middleware in SlimFrameWork 3


Solution

  • Did you try something like this?

    $requestIP = $request->getServerParam('REMOTE_ADDR');