web-profile

php get real IP address

<?php
if ( !empty( $_SERVER&#91;'HTTP_CLIENT_IP'&#93; ) ) { //check ip from share internet
	$ip = $_SERVER&#91;'HTTP_CLIENT_IP'&#93;;
} elseif ( !empty( $_SERVER&#91;'HTTP_X_FORWARDED_FOR'&#93; ) ) { // to check ip is pass from proxy, also could be used &#91;'HTTP_X_REAL_IP '&#93;
	$ip = $_SERVER&#91;'HTTP_X_FORWARDED_FOR'&#93;;
} else {
	$ip = $_SERVER&#91;'REMOTE_ADDR'&#93;;
}
?>

Check real IP address.

More complicated code to get IP address:

<?php
function get_ip_address(){
    foreach (array('HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR') as $key){
        if (array_key_exists($key, $_SERVER) === true){
            foreach (explode(',', $_SERVER&#91;$key&#93;) as $ip){
                $ip = trim($ip); // just to be safe

                if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false){
                    return $ip;
                }
            }
        }
    }
}

public function validate_ip($ip)
{
    if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) === false)
    {
        return false;
    }

    self::$ip = sprintf('%u', ip2long($ip)); // you seem to want this

    return true;
}



if( ! empty( $_SERVER&#91;'HTTP_X_FORWARDED_FOR'&#93; ) ) { // check for IPs passing through proxies
    $iplist = explode( ',', $_SERVER&#91;'HTTP_X_FORWARDED_FOR'&#93; );
    foreach( $iplist as $ip ) {
        if( $this->validate_ip( $ip ) ) {
            return $ip;
        }
    }
}

?>

Leave a Reply

Your email address will not be published.