Latox
Latox

Reputation: 4695

parsing url - php, check if scheme exists, validate url regex

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

Upvotes: 2

Views: 1066

Answers (3)

422
422

Reputation: 5770

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

Upvotes: 1

hamczu
hamczu

Reputation: 1774

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.

Upvotes: 0

deceze
deceze

Reputation: 522175

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.

Upvotes: 1

Related Questions