php to determine whether the IP address is legal

Get the real ip address

function get_ip(){
     //Determine whether the server allows $_SERVER
     if(isset($_SERVER)){
         if(isset($_SERVER[HTTP_X_FORWARDED_FOR])){
             $realip = $_SERVER[HTTP_X_FORWARDED_FOR];
         }elseif(isset($_SERVER[HTTP_CLIENT_IP])) {
             $realip = $_SERVER[HTTP_CLIENT_IP];
         }else{
             $realip = $_SERVER[REMOTE_ADDR];
         }
     }else{
         //Use getenv to get it if it is not allowed
         if(getenv("HTTP_X_FORWARDED_FOR")){
             $realip = getenv( "HTTP_X_FORWARDED_FOR");
         }elseif(getenv("HTTP_CLIENT_IP")) {
             $realip = getenv("HTTP_CLIENT_IP");
         }else{
             $realip = getenv("REMOTE_ADDR");
         }
     }
  
     return $realip;
}

There are two ways to verify whether the ip is reasonable

/**
     * Determine whether the IP input is legal
     * @param type $ip IP address
     * @return int equal to 1 is valid input 0 input is invalid
     */
    public static function isIp($ip) {
        if (preg_match('/^((?:(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d) ))\.){3}(?:25[0-5]|2[0-4]\d|((1\d{2})|([1 -9]?\d)))) $/', $ip)) {
            return 1;
        } else {
            return 0;
        }
    }
function checkIp($ip)
{
     $arr = explode('.',$ip);
     if(count($arr) != 4){
         return false;
     }else{
         for($i = 0;$i < 4;$i++){
             if(($arr[$i] <'0') || ($arr[$i] > '255')){
                 return false;
             }
         }
     }
     return true;
}

Leave a Reply

Your email address will not be published. Required fields are marked *

en_USEnglish