php filter_var() function

100 Views Asked by At

Hi is there anyone to know why in this following php code, "if" statement return true:

<!DOCTYPE html>
    <html>
    <body>

    <?php
    // Variable to check
    $ip = "2001:0db8:85a3:08d3:1319:8a2e:0370:7334";

    // Validate ip as IPv6
    if (!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) === false) {
    echo("$ip is a valid IPv6 address");
    } else {
    echo("$ip is not a valid IPv6 address");
    }
    ?>

    </body>
    </html>

but in below code return false:

<!DOCTYPE html>
     <html>
     <body>

     <?php
     // Variable to check
     $ip = "2001:0db8:85a3:08d3:1319:8a2e:0370:7334";

     // Validate ip as IPv6
     if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) === true) {
     echo("$ip is a valid IPv6 address");
     } else {
     echo("$ip is not a valid IPv6 address");
     }
     ?>

    < /body>
    </html>

what I mean is, in first code the condition is (false===false) but in second one the condition set to (true===true) and as I said, first one return true and second return false. why?

1

There are 1 best solutions below

3
deceze On

filter_var returns the filtered data, or false if the filter fails.

In the first case, you're turning successful values into false using !, so you get exactly false and false === false is true. In the second case, you compare "the filtered data" to true, and "2001:0db8:85a3:08d3:1319:8a2e:0370:7334" === true is not true.

Just leave off the hyper-explicit === check:

if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6))

This succeeds if the filter_var check returns something not falsey, and fails when filter_var explicitly returns false.