0

I'm using following function on my PHP site to get visitors IP

function getClientIP(){       
 if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)){
        return  $_SERVER["HTTP_X_FORWARDED_FOR"];  
 }else if (array_key_exists('REMOTE_ADDR', $_SERVER)) { 
        return $_SERVER["REMOTE_ADDR"]; 
 }else if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
        return $_SERVER["HTTP_CLIENT_IP"]; 
 } 

 return '';}

As I was not using any filter or validation on IP address earlier, few days back in our IP address column I have received some random strings (e.g. $IP_array) instead a valid IP address. And I think that request was sent using PHP script, I have tried several ways to spoof IP for my own site but each time a got my original IP or IP assigned VPN how it's possible to get some string instead IP.

GrumpyCrouton
  • 8,486
  • 7
  • 32
  • 71
Alex
  • 101
  • 1
  • 12
  • can you provide more examples of theses "random strings" –  Apr 25 '18 at 20:53
  • another was {$rand_IP_list} – Alex Apr 25 '18 at 21:05
  • See https://stackoverflow.com/questions/7623187/will-the-value-of-a-set-serverhttp-client-ip-be-an-empty-string – chris85 Apr 25 '18 at 21:09
  • looks like you can jsut do this: obviously they failed to set the variable correctly `curl --header "X-Forwarded-For: $fake_ip" "http://www.example.com"` –  Apr 25 '18 at 21:17
  • thanks @chris85 , i got the idea thanks smith for clarification , using HTTP_X_FORWARDED_FOR is compulsory for me to prevent random IP issue by some app user eg : opera mini , ucweb , puffin all these browsers are using their compression tech and assigning random IP to all its user each time they use app and to get their real IP i'm using HTTP_X_FORWARDED_FOR on top. is there any other way to prevent this spoofing. ? or we have to use $_SERVER["REMOTE_ADDR"] for everyone beside those browsers again we'll get into problem if someone changes their UA too – Alex Apr 25 '18 at 21:49
  • what are you using the IP for? other than light logging it never means much, wont identify an individual for example, –  Apr 25 '18 at 21:58
  • it's something similar to logging in , we are limiting number of download requests based on IP . – Alex Apr 26 '18 at 06:22

1 Answers1

0

you can try this:

<?PHP

function getUserIP()
{
    $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;
}


$user_ip = getUserIP();

echo $user_ip; // Output IP address [Ex: 192.168.1.150]


?>
Diego Avila
  • 700
  • 7
  • 24