-1

I want a system where the submitted data from my input field has to be a URL and start with 'http://' or 'https://' in PHP. But when I submit the form it keeps alerting 'Invalid Link' can it be fixed?

    <?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>";
}

?>

Thanks for your time.

KABULPUT
  • 25
  • 7

2 Answers2

0

If your goal is to check if a certain string is a URL and a valid one at that the simplest way to check would be using validate filters more specifically FILTER_VALIDATE_URL.

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

}
else
{
    // url is no valid
}

However do note that strings that do not start with http or https are not considered valid urls. This is not any sort of bug in PHP or in any other language it's how the Uniform Resource Identifier works.


If your goal is to check strictly if a string starts with http or https and only that you can simply use strpos

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

Note that I'm using === 0 that's because strpos returns the position of the string or false if not found. You want to check if the string starts with http or https.


There's also the route of regex. See this question.

Andrei
  • 3,434
  • 5
  • 21
  • 44
0

That is because your pattern consists of a complete url that you are parsing in the regex via a variable and you are not escaping the // in the http:// you need to use preg_quote() like below

if(strlen($Link) <= 5 || !preg_match('/' . preg_quote($contains, '/') . '/', $Link)){
    echo "<script> alert('INVALID LINK!') </script>";
    exit;
}
Muhammad Omer Aslam
  • 22,976
  • 9
  • 42
  • 68