How to get client IP address in Laravel 5+

前端 未结 18 2612
你的背包
你的背包 2020-11-27 11:11

I am trying to get the client\'s IP address in Laravel.

It is easy to get a client\'s IP in PHP by using $_SERVER[\"REMOTE_ADDR\"]. It is working fine

相关标签:
18条回答
  • 2020-11-27 12:01

    For Laravel 5 you can use the Request object. Just call its ip() method, something like:

    $request->ip();
    
    0 讨论(0)
  • 2020-11-27 12:03
      $ip = $_SERVER['REMOTE_ADDR'];
    
    0 讨论(0)
  • 2020-11-27 12:05

    If you want client IP and your server is behind aws elb, then user the following code. Tested for laravel 5.3

    $elbSubnet = '172.31.0.0/16';
    Request::setTrustedProxies([$elbSubnet]);
    $clientIp = $request->ip();
    
    0 讨论(0)
  • 2020-11-27 12:06

    Use request()->ip().

    From what I understand, since Laravel 5 it's advised/good practice to use the global functions like:

    response()->json($v);
    view('path.to.blade');
    redirect();
    route();
    cookie();
    

    And, if anything, when using the functions instead of the static notation my IDE doesn't light up like a Christmas tree.

    0 讨论(0)
  • 2020-11-27 12:06

    If you have multiple layer proxies just like CDN + Load Balancer.
    Using Laravel Request::ip() function will get right-most proxy IP but not client IP.
    You may try following solution.

    app/Http/Middleware/TrustProxies.php

    protected $proxies = ['0.0.0.0/0'];
    

    Reference: https://github.com/fideloper/TrustedProxy/issues/107#issuecomment-373065215

    0 讨论(0)
  • 2020-11-27 12:10

    There are two things to take care of:

    1. Get a helper function that returns a Illuminate\Http\Request and call the ->ip() method:

      request()->ip();
      
    2. Think of your server configuration, it may use a proxy or load-balancer, especially in an AWS ELB configuration.

    If this is your case you need to follow "Configuring Trusted Proxies" or maybe even set a "Trusting All Proxies" option.

    Why? Because being your server will be getting your proxy/load-balancer IP instead.

    If you are on the AWS balance-loader, go to App\Http\Middleware\TrustProxies and make $proxies declaration look like this:

    protected $proxies = '*';
    

    Now test it and celebrate because you just saved yourself from having trouble with throttle middleware. It also relies on request()->ip() and without setting "TrustProxies" up, you could have all your users blocked from logging in instead of blocking only the culprit's IP.

    And because throttle middleware is not explained properly in the documentation, I recommend watching "laravel 5.2 tutorial for beginner, API Rate Limiting"

    Tested in Laravel 5.7

    0 讨论(0)
提交回复
热议问题