How to validate IPv6 using filter_var()?

时间:2016-08-31 17:23:59

标签: php

I am trying to filter IPv6 from the input. I tried to input IPv4 in the field in the form, in this case the else statement must be executed but the condition was true. I mean both IPV4 & IPV6 are true.

How can I make that example more specific?

php:

<?php
$input = $_POST['test'];

$opt = array (

        'options' => array (),
        'flags'   => FILTER_FLAG_IPV6
);

if (filter_var($input,FILTER_VALIDATE_IP,$opt) !== FALSE) {
    echo 'Good (' . $input . ') is ip version 6';
} else {

    echo 'Sorry (' . $input . ') is not ip version 6';
}

form:

<form action="checkinput.php" method="post">
  <input type="text" name="test">
  <input type="submit" value="Send">
</form>

2 个答案:

答案 0 :(得分:2)

You can put flag inside filter function:

<?php
$input = $_POST['test'];

if (filter_var($input, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) !== FALSE) {
    echo 'Good (' . $input . ') is ip version 6';
} else {

    echo 'Sorry (' . $input . ') is not ip version 6';
}

Or you can specify options array like this:

$opt = array (
    'options' => 'FILTER_FLAG_IPV6',
);

答案 1 :(得分:1)

This could definitely be caused by the typo falgs instead of flags in your $opt array. If this isn't just a typo in your question, it would cause the filter_var to ignore the invalid options (this doesn't cause any errors or warnings) and validate using FILTER_VALIDATE_IP with no options, so that either V4 or V6 would work.