Coder Perfect

In Laravel 5+, how can I get the client’s IP address?

Problem

In Laravel, I’m trying to acquire the client’s IP address.

In PHP, $_SERVER[“REMOTE ADDR”] makes obtaining a client’s IP address simple. When I use the same thing in Laravel, it returns the server IP instead of the visitor’s IP, which is OK in core PHP.

Asked by Amrinder Singh

Solution #1

Taking a look at the Laravel API:

Request::ip();

It uses the getClientIps method from the Symfony Request Object internally:

public function getClientIps()
{
    $clientIps = array();
    $ip = $this->server->get('REMOTE_ADDR');
    if (!$this->isFromTrustedProxy()) {
        return array($ip);
    }
    if (self::$trustedHeaders[self::HEADER_FORWARDED] && $this->headers->has(self::$trustedHeaders[self::HEADER_FORWARDED])) {
        $forwardedHeader = $this->headers->get(self::$trustedHeaders[self::HEADER_FORWARDED]);
        preg_match_all('{(for)=("?\[?)([a-z0-9\.:_\-/]*)}', $forwardedHeader, $matches);
        $clientIps = $matches[3];
    } elseif (self::$trustedHeaders[self::HEADER_CLIENT_IP] && $this->headers->has(self::$trustedHeaders[self::HEADER_CLIENT_IP])) {
        $clientIps = array_map('trim', explode(',', $this->headers->get(self::$trustedHeaders[self::HEADER_CLIENT_IP])));
    }
    $clientIps[] = $ip; // Complete the IP chain with the IP the request actually came from
    $ip = $clientIps[0]; // Fallback to this when the client IP falls into the range of trusted proxies
    foreach ($clientIps as $key => $clientIp) {
        // Remove port (unfortunately, it does happen)
        if (preg_match('{((?:\d+\.){3}\d+)\:\d+}', $clientIp, $match)) {
            $clientIps[$key] = $clientIp = $match[1];
        }
        if (IpUtils::checkIp($clientIp, self::$trustedProxies)) {
            unset($clientIps[$key]);
        }
    }
    // Now the IP chain contains only untrusted proxies and the client IP
    return $clientIps ? array_reverse($clientIps) : array($ip);
} 

Answered by samlev

Solution #2

If you’re using a load balancer, Laravel’s Request:: method will help you. The IP address of the balancer is always returned by 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;
                }
            }
        }
    }
    return request()->ip(); // it will return server ip when no client ip found
}

Furthermore, I recommend that you use Laravel’s throttle middleware with caution: It also makes advantage of Laravel’s Request::ip(), so all of your visitors will be identified as the same person, and you’ll fast reach the throttle limit. This happened to me in real life, and it caused a lot of problems.

To fix this:

Illuminate\Http\Request.php

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

You may now use Request::ip() to get the real IP address in production.

Answered by Sebastien Horin

Solution #3

Use request()->ip().

According to my understanding, since Laravel 5, it’s recommended/best practice to use global functions like:

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

And, if anything, my IDE doesn’t light up like a Christmas tree when I use functions instead of static notation.

Answered by Stan Smulders

Solution #4

Add namespace

use Request;

After that, call the function.

Request::ip();

Answered by shalini

Solution #5

You can utilize the Request object in Laravel 5. Simply call its ip() method, such as:

$request->ip();

Answered by Todor Todorov

Post is based on https://stackoverflow.com/questions/33268683/how-to-get-client-ip-address-in-laravel-5