Vignesh Palanichamy
Vignesh Palanichamy

Reputation: 101

how to get public ip of the client in php

I have to get public IP of the remote system in php. I have tried

$_SERVER['REMOTE_ADDR']

getenv('REMOTE_ADDR');

but is always returning the private IP. Help to fix it.

Upvotes: 0

Views: 1386

Answers (2)

Louiela
Louiela

Reputation: 34

private function getIP()
{
    $client  = @$_SERVER['HTTP_CLIENT_IP'];
    $forward = @$_SERVER['HTTP_X_FORWARDED_FOR'];
    $remote  = $_SERVER['REMOTE_ADDR'];

    if(filter_var($client, FILTER_VALIDATE_IP))
    {
        $ip = $client;
    }
    elseif(filter_var($forward, FILTER_VALIDATE_IP))
    {
        $ip = $forward;
    }
    else
    {
        $ip = $remote;
    }

    return $ip;
}
echo getIP();

Upvotes: 0

Claudio Bredfeldt
Claudio Bredfeldt

Reputation: 1422

Try this:

$ip = !empty($_SERVER['HTTP_CLIENT_IP']) ? $_SERVER['HTTP_CLIENT_IP'] : (!empty($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR']);

Warning: you should extend it and sanitize, since headers can be easily manipulated.

Upvotes: 1

Related Questions