3

I need a PHP validation function for URL with Query string (parameters seperated with &). currently I've the following function for validating URLs

$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})*)?$/';

echo preg_match($pattern, $url);

This function correctly validates input like

google.com www.google.com http://google.com http://www.google.com ...etc

But this won't validate the URL when it comes with parameters (Query string). for eg.

http://google.com/index.html?prod=gmail&act=inbox

I need a function that accepts both types of URL inputs. Please help. Thanks in advance.

2 Answers 2

3

A simple filter_var

if(filter_var($yoururl, FILTER_VALIDATE_URL))
{
  echo 'Ok';
}

might do the trick, although there are problems with url not preceding the schema: http://codepad.org/1HAdufMG

You can turn around the issue by placing an http:// in front of urls without it.
As suggested by @DaveRandom, you could do something like:

$parsed = parse_url($url); 
if (!isset($parsed['scheme'])) $url = "http://$url";

before feeding the filter_var() function.

Overall it's still a simpler solution than some extra-complicated regex, though..

It also has these flags available:

FILTER_FLAG_PATH_REQUIRED FILTER_VALIDATE_URL Requires the URL to contain a path part. FILTER_FLAG_QUERY_REQUIRED FILTER_VALIDATE_URL Requires the URL to contain a query string.

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

2 Comments

FTR, I think the most sensible approach to making sure the scheme is present would be $parsed = parse_url($str); if (!isset($parsed['scheme'])) $url = "http://$url";
I Used Parse_url for checking whether query exists in URI. Almost Worked..:)
0

http://php.net/manual/en/function.parse-url.php

Some might think this is not a 100% bullet-proof,
but you can give a try as a start

2 Comments

Although This function is not meant to validate the given URL, it only breaks it up into the above listed parts.
@DamienPirsy Indeed, I was going to answer with exactly this, until I started playing with it and discovered that I couldn't actually come up with anything that would make it return false. Even passing "\x00" or "[email protected]" doesn't break it...

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.