2

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

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.