Validate non-localhost IP

validate_ip.inc.php
    /**
     * Checks for a valid non-127-IP
     * @param string $ip IP-Address
     * @return bool TRUE if IP is valid and not localnet, FALSE if invalid or local
     */
    function isValidIP($ip) {
        $ip = trim($ip);
        $isvalid = true;
        $i = split('\.', $ip, 4);
        $iv = array();
 
        foreach ($i as $key=>$val) {
            $iv[$key] = intval($val);
            if (strlen($val)>3 || strlen($val)<=0 || $iv[$key]<0 || $iv[$key]>255) {
                $isvalid = false;
            }
        }
        if ($iv[0]==0) {
            $isvalid = false;
        }
        if ($iv[0]==127 && $iv[1]==0 && $iv[2]==0 && $iv[3]==1) {
            $isvalid = false;
        }
        return $isvalid;
    }
 
    /**
     * Returns the IP of the accessing client PC, if possible
     * @return string|bool The client IP or FALSE on error.
     */
    function getClientIP() {
        $addr = $_SERVER['HTTP_X_FORWARDED_FOR'];
        if (!empty($addr) && isValidIP($addr)) return $addr;
        $addr = $_SERVER['HTTP_CLIENT_IP'];
        if (!empty($addr) && isValidIP($addr)) return $addr;
        $addr = $_SERVER['REMOTE_ADDR'];
        if (!empty($addr) && isValidIP($addr)) return $addr;
        return false;
    }

 
snippets/php/validateip.txt · Last modified: 2010-01-15 14:37.07 by mbirth
 
Except where otherwise noted, content on this wiki is licensed under the following license:CC Attribution-Noncommercial-Share Alike 3.0 Unported
Recent changes RSS feed Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki Contents powered by Club-Mate Contents powered by BassDrive.com Labelled with ICRA