4

I'm unable to get the IP address of the client which I need to determine his current location.

I've used request->ip(), $_SERVER['REMOTE_ADDR'] and I always get a 127.0.0.1 result which is not what I want.

What am I doing wrong?

Bruno Teixeira
  • 565
  • 4
  • 11
  • 25

5 Answers5

6

Sometimes your clients use your application through a proxy, so you should not depend on $_SERVER['REMOTE_ADDR'].

Check out this link (with a little concern on securities):
How to get the client IP address in PHP?

Community
  • 1
  • 1
Leo Khoa
  • 897
  • 7
  • 8
5

request->ip() will give you client IP. You're getting 127.0.0.1 in because you're trying to access your local project from the same machine.

Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279
  • `$_SERVER['REMOTE_ADDR']` is the client IP not the server IP. – Devon Bessemer Dec 22 '16 at 18:38
  • You're right. I've answered [`SERVER_ADDR` related question recently](http://stackoverflow.com/questions/41258208/how-to-get-the-server-ip-with-laravel/41258486#41258486), so I automatically read it as `SERVER_ADDR` ) Thanks, I've fixed my answer. – Alexey Mezenin Dec 22 '16 at 18:48
0

I found a way how to fix it. But beware that you have to change it before going production!!

Read this part: https://laravel.com/docs/5.7/requests#configuring-trusted-proxies

And now just add this:

class TrustProxies extends Middleware
{
    /**
     * The trusted proxies for this application.
     *
     * @var array
     */
    protected $proxies = '*';

Now request()->ip() gives you the correct ip

Philipp Mochine
  • 4,351
  • 10
  • 36
  • 68
0

You can try this:

function get_ip() {
    $keys = array('HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR');

    foreach ($keys as $key) {
        if (array_key_exists($key, $_SERVER) === true) {
            foreach (explode(',', $_SERVER[$key]) as $ip) {
                if (filter_var($ip, FILTER_VALIDATE_IP) !== false) {
                    return $ip;
                }
            }
        }
    }
}
Max S.
  • 1,383
  • 14
  • 25
-2

There is client IP address this code($_SERVER['REMOTE_ADDR']) applied online project then it will work successfully . it will try..

Mohammad Kanan
  • 4,452
  • 10
  • 23
  • 47
Dharmik Unagar
  • 58
  • 1
  • 2
  • 8