skip to Main Content

I am trying to get client IP with $request->getClientIp(); and it returns 172.19.0.2, but that is not my public IP.

I stumbled upon this doc to set up trusted proxies so I tried doing like this:

// web/app_dev.php
// ...
$request = Request::createFromGlobals();
// tell Symfony about your reverse proxy
Request::setTrustedProxies(['172.19.0.0/8'], Request::HEADER_X_FORWARDED_ALL);
$response = $kernel->handle($request);
// ...

But that did not fix the issue.

What am I doing wrong?

2

Answers


  1. "Public IP"? As explained in "How can I get client real ip address in PHP?"

    Typically a Public IP address can be found when your service is reached over the internet.

    Your PHP app has no clue about your public IP as it is in the private network. Public IP is assigned to you by your ISP/Router. Router NATs the private IPs so only 1 IP is allocated to your private network.

    That means you would need to rely to your reverse proxy (NGiNX in your case) to populate correctly HTTP_X_FORWARDED_FOR, which you can try and read:

    $IParray=array_values(array_filter(explode(',',$_SERVER['HTTP_X_FORWARDED_FOR'])));
    

    Or use this GetClientIP() function, which would check for:

    • HTTP_CF_CONNECTING_IP
    • HTTP_X_REAL_IP
    • HTTP_CLIENT_IP
    • HTTP_X_FORWARDED_FOR
    • HTTP_X_FORWARDED
    • HTTP_X_CLUSTER_CLIENT_IP
    • HTTP_FORWARDED_FOR
    • HTTP_FORWARDED
    • REMOTE_ADDR

    Again, it depends on what the internet-facing reverse-proxy has set.

    Login or Signup to reply.
  2. In my opinion, you use docker container + nginx proxies. So, here seems, IP send to software incorrectly. In that case, you can use nginx configuration to pass whole headers from client to the container (port). Let’s mean that, we have software (container) which work over 9001 port in localhost. Then we must set configuration like that:

    
     location / {
            try_files $uri $uri/ /index.php?$query_string;
             proxy_set_header        Host               $host;
             proxy_set_header        X-Real-IP          $remote_addr;
             proxy_set_header        X-Forwarded-For    $proxy_add_x_forwarded_for;
        }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search