Pixel Pixel -4 years ago 209
PHP Question

Not common IP address

I have a problem when I'm trying to parse the visitor IP, 1 / 500 users had a bad IP as you can see in the logs.

Can someone explain to me if I make a mistake in my code?

My code:

if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
} else if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$ip = $_SERVER['REMOTE_ADDR'];
}

$ip = str_replace(' ','', $ip);

if(filter_var($ip, FILTER_VALIDATE_IP) === false){
Log::error('IP : '.$ip);
return Redirect::to($link->white_url, 301);
}


Logs :

[2017-03-23 16:36:15] production.ERROR: IP : 192.168.5.173,sams04818.orl,sams04818.orl
[2017-03-23 16:36:30] production.ERROR: IP : 192.168.5.173,sams04818.orl,sams04818.orl
[2017-03-23 16:37:15] production.ERROR: IP : 192.168.4.217,wmt03459.chi,wmt03459.chi
[2017-03-23 16:39:01] production.ERROR: IP : 77.154.224.155,77.154.224.155
[2017-03-23 17:31:03] production.ERROR: IP : 192.168.5.80,mcd03610.phx,mcd03610.phx
[2017-03-23 17:09:09] production.ERROR: IP : 92.90.16.110,92.90.16.110

Answer Source

The X-Forwarded-For (XFF) header would contain multiple IP addresses if the client request has passed through multiple proxies. XFF is also commonly used by load balancers.

The first IP address in the string, however, belongs to the origin. You could extract it.

if(strpos($ip,','))
    $ip = substr($ip, 0, strpos($ip,','));

Reference: https://en.wikipedia.org/wiki/X-Forwarded-For#Format

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download