为什么这个preg_match几乎可以通过什么?

时间:2015-11-02 03:26:44

标签: php

我尝试使用preg_match来测试网址。

这是我的代码的一部分:

$url_array[0] = $_REQUEST['url0'];
$url_array[1] = $_REQUEST['url1'];
$url_array[2] = $_REQUEST['url2'];
$url_array[3] = $_REQUEST['url3'];
$url_array[4] = $_REQUEST['url4'];

foreach ($url_array as &$val) {
    if(substr($val, 0, 7) != "http://" && substr($val, 0, 8) != "https://" && substr($val, 0, 4) != "www." && $val != "") {
        $val = "http://".$val;
    }
}

foreach ($url_array as &$val) {
    if(!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i", $val) && $val != "") {
    header("Location: {$_SERVER["PHP_SELF"]}?p=home&x=urlerror");
    exit;
    }
}

问题是它允许通过http://i'll just use whatever ;G characters here and it'll be fine之类的随机内容作为网址。这是为什么?

谢谢!
-G

最终结论:

URL排序的正则表达很糟糕,我为此交换了它:

foreach ($url_array as &$val) {
    if(!filter_var($val, FILTER_VALIDATE_URL) === true && $val != "") {
        header("Location: {$_SERVER["PHP_SELF"]}?p=home&x=urlerror");
        exit;
    }
}

它似乎完美无缺。 :)

感谢@Passerby和@ Chris85

0 个答案:

没有答案