Cómo obtener la dirección IP del cliente en Laravel 5.1?


Estoy tratando de obtener la dirección IP del cliente en Laravel. Como todos sabemos, es mucho más fácil obtener la IP de un cliente en PHP usando $_SERVER["REMOTE_ADDR"].

Está funcionando bien en core PHP, pero cuando uso lo mismo en Laravel, entonces da IP del servidor en lugar de IP del visitante.

Author: halfer, 2015-10-21

10 answers

Mirando la API Laravel :

Request::ip();

Internamente, utiliza el método getClientIps desde el Objeto de solicitud Symfony :

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);
}
 113
Author: samlev,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-21 20:35:04

Uso request()->ip() :)

Desde Laravel 5 es (por lo que entiendo) aconsejable / buena práctica usar las funciones globales como:

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

Usted consigue el punto: -) Y en todo caso, cuando se utiliza las funciones (en lugar del notarion estático) mi IDE no se enciende como un árbol de Navidad; -)

 47
Author: Stan Smulders,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-23 06:41:24

Si está bajo un balanceador de carga

Laravel's \Request::ip() siempre devuelve la IP del equilibrador

            echo $request->ip();
            // server ip

            echo \Request::ip();
            // server ip

            echo \request()->ip();
            // server ip

            echo $this->getIp(); //see the method below
            // clent ip

Este método personalizado devuelve la ip real del cliente:

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;
                }
            }
        }
    }
}

Más: Si utiliza el middleware del acelerador de Laravel

Además de esto, le sugiero que tenga mucho cuidado con el middleware de Laravel throttle: También utiliza Laravel Request::ip(), por lo que todos sus visitantes se identificarán como el mismo usuario y se golpeará el acelerador limite muy rápidamente. Experiencia en vivo...esto me llevó a grandes problemas...

Para arreglar esto:

Ilumina\Http\Request.php

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

Ahora también puede usar Request::ip(), que debería devolver la IP real en producción

 39
Author: Sebastien Horin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-12 08:40:46

Añadir espacio de nombres

use Request;

Luego llame a la función

Request::ip();
 20
Author: shalini,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-19 09:42:07

Para Laravel 5 puede usar el objeto Request. Simplemente llame a su método ip (). Algo como:

$request->ip();

 11
Author: TodStoychev,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-01 14:21:23

En Laravel 5

public function index(Request $request) {
  $request->ip();
}
 9
Author: Govind Samrow,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-21 07:16:02

En la versión laravel 5.4 no podemos llamar a ip static esta es una forma correcta de obtener ip user

 use Illuminate\Http\Request;

public function contactUS(Request $request)
    {
        echo $request->ip();
        return view('page.contactUS');
    }
 2
Author: Vahid Alvandi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-30 09:12:14

Si desea la IP del cliente y su servidor está detrás de aws elb, utilice el siguiente código. Probado para laravel 5.3

$elbSubnet = '172.31.0.0/16';
Request::setTrustedProxies([$elbSubnet]);
$clientIp = $request->ip();
 2
Author: Aung Bo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-24 03:18:48

En la nueva versión se puede obtener con request helper

request()->ip();
 0
Author: DsRaj,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-28 04:51:49

Cuando queremos el ip_address del usuario:

$_SERVER['REMOTE_ADDR']

Y desea la dirección del servidor:

$_SERVER['SERVER_ADDR']
 -3
Author: shashikant parmar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-10 06:02:17