Is this a good way to validate a posted URL?

if (filter_var($_POST['url'], FILTER_VALIDATE_URL)){
    echo "valid url";
}else{
    echo "invalid url";
}

This is what I wrote to start with, as I could show multiple error messages with it:

function validateURL($url)
{
$pattern = '/^(([\w]+:)?\/\/)?(([\d\w]|%[a-fA-f\d]{2,2})+(:([\d\w]|%[a-fA-f\d]{2,2})+)?@)?([\d\w][-\d\w]{0,253}[\d\w]\.)+[\w]{2,4}(:[\d]+)?(\/([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)*(\?(&?([-+_~.\d\w]|%[a-fA-f\d]{2,2})=?)*)?(#([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)?$/';
return preg_match($pattern, $url);
}

$result = validateURL($_POST['url']);
if ($result == "1"){
 $scheme = parse_url($_POST['url'], PHP_URL_SCHEME);
 if (isset($scheme)){
  echo $scheme . "://" . parse_url($_POST['url'], PHP_URL_HOST);
 }else{
  echo "error you did not enter http://";
 }
}else{
 echo "your url is not a valid format";
}
share|improve this question

78% accept rate
feedback

3 Answers

up vote 1 down vote accepted

I'd simply go for the build-in FILTER_VALIDATE_URL and use a generic error message like:

Invalid URL. Please remember to input http:// as well.

If you're nice you could check if the first 7/8 letters are http:// or https:// and prepend them if not.

Coming up with and maintaining such a RegEx is not something you should get into if the problem is already solved. There's also usually no need to be any more detailed in the error message, unless you're in the business of explaining URL formats.

share|improve this answer
feedback

Have you checked this out Kyle, http://phpcentral.com/208-url-validation-in-php.html

share|improve this answer
feedback

I think simple

filter_var($var, FILTER_VALIDATE_URL)

and checking the protocol by strpos() is enough because user can, if wants to, give you the wrong (which does not exists) url.

Of course you can check if domain exists and return valid http status but I think it is little overstatement.

share|improve this answer
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.