简体   繁体   中英

PHP validate IP address

<?php
$subdomain ='hello.cheapantivirus.me';
        $ns1 = 'ns01.000webhost.com';

$host = "@$ns1 $subdomain";
$ip = `/usr/bin/dig $host +short A`;

 echo $ip; // output is 31.170.161.67

 $ip3 = '84.8.161.5';

 if(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
   echo "valid"; 
}
else {
  echo " not valid"; // the $ip is invalid
}


 if(filter_var($ip3, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
   echo "valid"; // somehow this one is valid
}
else {
  echo " not valid";
}
?>

My question is why is $ip filter is being shown as invalid but $ip3 when I assign the IP manually the $ip3 filter is being shown as valid. Help me please?

The command line output may contain trailing spaces or line breaks.

Try

$ip = trim($ip);

before doing the validation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM