Showing posts with label ip address. Show all posts
Showing posts with label ip address. Show all posts

Thursday, 8 September 2016

PHP Function to Validate IP Address

Simple php function to validate IP address and check whether it is in private network range. Ip validation in php for easy validating of IPv4 address.

function validateIpAddress($ip) {
    if(strtolower($ip)==='unknown' || $ip=="") return false;
    $ip = ip2long($ip); // get ipv4 network address
    if($ip!==false && $ip!==-1) {
        $ip = sprintf('%u', $ip);
        // check private network range
        if ($ip >= 0 && $ip <= 50331647) return false;
        if ($ip >= 167772160 && $ip <= 184549375) return false;
        if ($ip >= 2130706432 && $ip <= 2147483647) return false;
        if ($ip >= 2851995648 && $ip <= 2852061183) return false;
        if ($ip >= 2886729728 && $ip <= 2887778303) return false;
        if ($ip >;= 3221225984 && $ip <= 3221226239) return false;
        if ($ip >;= 3232235520 && $ip <= 3232301055) return false;
        if ($ip >= 4294967040) return false;
    }
    return true;
}

Thursday, 21 July 2016

PHP Function to get IP address of a client

Easy and simple function to get ip address of client address. Below function gets the clients system ip address in normal cases and if the client is present in a proxy then it will get the real ip address.

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


Use the above php code snippet to show the ip address of the client in your webpage.