PHP check if url is valid

3k Views Asked by At

I wonder what would be the best way in php to check if provided url is valid... At first I tried with:

filter_var($url, FILTER_VALIDATE_URL) === false

But it does not accept www.example.com (without protocol). So I tried with a simple modification:

protected function checkReferrerUrl($url) {
    if(strpos($url, '://') == false) {
        $url = "http://".$url;
    }
    if(filter_var($url, FILTER_VALIDATE_URL) === false) {
        return false;
    }
    return true;
}

Now it works fine with www.example.com but also accepts simple foo as it converts to http://foo. However though this is not a valid public url I think... so what would you suggest? Go back to traditional regexp?

2

There are 2 best solutions below

0
On BEST ANSWER

I recommend, that you do not use filter_var with type URL. There are much more side-effects. For example, these are valid URLs according to filter_var:

http://example.com/"><script>alert(document.cookie)</script>
http://example.ee/sdsf"f

Additionally FILTER_VALIDATE_URL does not support internationalized domain names (IDN).

I recommend using a regex combined with some ifs afterwards (f.e. for the domain) for security reasons. Without the security aspect I am using parse_url to take my parts. But this function has a similar issue, when the scheme (no http/https) is missing.

4
On

Use this

<?php
$url = 'www.example.com';

if(validateURL($url)){
       echo "Valid";
    }else{
        echo "invalid";
    }

function validateURL($URL) {
      $pattern_1 = "/^(http|https|ftp):\/\/(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+.(com|org|net|dk|at|us|tv|info|uk|co.uk|biz|se)$)(:(\d+))?\/?/i";
      $pattern_2 = "/^(www)((\.[A-Z0-9][A-Z0-9_-]*)+.(com|org|net|dk|at|us|tv|info|uk|co.uk|biz|se)$)(:(\d+))?\/?/i";       
      if(preg_match($pattern_1, $URL) || preg_match($pattern_2, $URL)){
        return true;
      } else{
        return false;
      }
    }
?>

Try this one too

<?php

// Assign URL to $URL variable
$url = 'http://example.com';

// Check url using preg_match
if (preg_match("/^(https?:\/\/+[\w\-]+\.[\w\-]+)/i",$url)){
    echo "Valid";
    }else{
        echo "invalid";
    }

?>