Search code examples
phpnetwork-programmingipipv4filter-var

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?


Solution

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

    Try

    $ip = trim($ip);
    

    before doing the validation.