检查提交的表单数据是否是链接,并以某些单词开头

时间:2018-07-07 22:19:21

标签: php html5

我想要一个系统,其中输入字段中提交的数据必须是URL,并在PHP中以“ http://”或“ https://”开头。但是当我提交表单时,它会不断提醒“无效链接”,可以修复它吗?

    <?php
    if(isset($_POST['Title'])){
        $Title=$_POST['Title'];
    }if(isset($_POST['Description'])){
        $Description=$_POST['Description'];
    }if(isset($_POST['Link'])){
        $Link=$_POST['Link'];
    }
    if(strlen($Title) <= 5){
        echo "<script> alert('Title should be more than 5 characters!')</script>";
        exit;
    }
    if(strlen($Description) <= 5){
        echo "<script> alert('Description should be more than 5 characters!')</script>";
        exit;
    }
    $contains = "https://drive.google.com/";

    if(strlen($Link) <= 5 || !preg_match("/\b($contains)\b/", $Link)){
        echo "<script> alert('INVALID LINK!') </script>";
        exit;
    }
    else{
    echo "<script> alert('DONE!') </script>";
}

?>

感谢您的时间。

2 个答案:

答案 0 :(得分:0)

如果您的目标是检查某个字符串是否为URL,并且是有效字符串,那么最简单的检查方法是使用validate filters,更具体地说是FILTER_VALIDATE_URL

if(filter_var('https://google.com', FILTER_VALIDATE_URL))
{
    // Url is valid

}
else
{
    // url is no valid
}

但是请注意,httphttps开头的字符串不被视为有效的网址。这不是PHP或任何其他语言中的任何类型的错误,而是Uniform Resource Identifier的工作方式。


如果您的目标是严格检查字符串是否以httphttps开头,并且仅使用strpos

if(strpos($url, `http`) === 0 || strpos($url, `https`) === 0) {
    // the url starts with http or https
    // strpos
}

请注意,我使用=== 0是因为strpos返回字符串的位置,如果找不到则返回false。您要检查字符串http还是https开头


还有正则表达式的路由。请参阅this问题。

答案 1 :(得分:0)

这是因为您的模式包含要通过变量在正则表达式中解析的完整URL,并且您没有在//中转义http://,而需要使用preg_quote()像下面一样

if(strlen($Link) <= 5 || !preg_match('/' . preg_quote($contains, '/') . '/', $Link)){
    echo "<script> alert('INVALID LINK!') </script>";
    exit;
}
相关问题