0

I'm creating a little script where i wanna check whether a specific url is valid. I've found a this function below to do this. However this only returns true if it starts with http:// is it possible to make so that it also accept a url like following

www.example.com
example.com

Code:

if (filter_var('http://www.example.com', FILTER_VALIDATE_URL) !== FALSE) {
}
Peter Pik
  • 11,023
  • 19
  • 84
  • 142
  • http://stackoverflow.com/questions/2280394/how-can-i-check-if-a-url-exists-via-php – sergio May 18 '15 at 15:59
  • use regex to validate, check answer. – vps May 18 '15 at 16:00
  • Check this answer: http://stackoverflow.com/a/16436491/1635676 – Touqeer Shafi May 18 '15 at 16:00
  • possible duplicate of [validate url with regular expressions](http://stackoverflow.com/questions/16434017/validate-url-with-regular-expressions) – Roan May 18 '15 at 16:04
  • `filter_var` is a good choice unlike creating crippled self-made regex validators. If you want it to tolerate the missing schema, then just check if the string starts with http(s?)://, and add it yourself if it doesn't. – disjunction May 18 '15 at 16:47

2 Answers2

0

I think the easiest way is to, if the check fails, just slap http:// in front of it and try that, too. If that works, chances are quite good it's a valid http url that just left the http:// part out. The function filter_var() is definitely the proper way to do it. Writing your own regexes, trying to download an address, etc., is completely unnecessary.

Joel Hinz
  • 24,719
  • 6
  • 62
  • 75
0

Try following regex approach...

function is_url_valid($url)
{
    if(! preg_match('/^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/', $url))
    {
        return false;    
    }
    else return true;
}
vps
  • 422
  • 2
  • 6