How to get client IP address in Laravel 5+

前端 未结 18 2734
你的背包
你的背包 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 11:52

    If you are under a load balancer, Laravel's \Request::ip() always returns the balancer's IP:

                echo $request->ip();
                // server ip
    
                echo \Request::ip();
                // server ip
    
                echo \request()->ip();
                // server ip
    
                echo $this->getIp(); //see the method below
                // clent ip
    

    This custom method returns the real client ip:

    public function getIp(){
        foreach (array('HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR') as $key){
            if (array_key_exists($key, $_SERVER) === true){
                foreach (explode(',', $_SERVER[$key]) as $ip){
                    $ip = trim($ip); // just to be safe
                    if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false){
                        return $ip;
                    }
                }
            }
        }
    }
    

    In addition to this I suggest you to be very careful using Laravel's throttle middleware: It uses Laravel's Request::ip() as well, so all your visitors will be identified as the same user and you will hit the throttle limit very quickly. I experienced this live and this caused big issues.

    To fix this:

    Illuminate\Http\Request.php

        public function ip()
        {
            //return $this->getClientIp(); //original method
            return $this->getIp(); // the above method
        }
    

    You can now also use Request::ip(), which should return the real IP in production.

提交回复
热议问题