detecting visitor’s real IP address

I use this block of codes to detect my visitors real IP address. Sometimes users connect to my site via HTTP proxy. if we rely only on $_SERVER[‘REMOTE_ADDR’], our script would easily spoofed by users.

Here’s the code:

$ipaddress=""; //this variable will hold user's real IP address
if (($_SERVER['HTTP_X_FORWARDED_FOR']!='')&&(substr($_SERVER['HTTP_X_FORWARDED_FOR'], 0, 7)!='127.0.0')&&(substr($_SERVER['HTTP_X_FORWARDED_FOR'], 0, 7)!='192.168')&&(substr($_SERVER['HTTP_X_FORWARDED_FOR'], 0, 3)!='10.')) {
    $ipaddress=trim(end(explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])));
    if (($ipaddress=='')||(substr($ipaddress, 0, 7)=='127.0.0')||(substr($ipaddress, 0, 7)=='192.168')||(substr($ipaddress, 0, 3)=='10.')||($ipaddress=='unknown')) {
} else {

The codes rely on $_SERVER[‘HTTP_X_FORWARDED_FOR’] for proxy connection. Check for local IP block (private network) and fall back to¬†$_SERVER[‘REMOTE_ADDR’] if fail. You may also check $_SERVER[‘HTTP_CLIENT_IP’] variable but in my case, it often return local IP address (private network). After getting this real IP address, you might do some geo IP related services.
Of course this script can’t detect visitor’s real IP address if he/she is using high anonymous proxy server, VPN or SOCKS5 proxy server. Check your browsing anonymity to make sure.

Comments are closed.