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.

share|improve this question

2 Answers

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.

share|improve this answer
1  
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"; – DaveRandom Dec 14 '11 at 13:48
Thankyou, updated with your comment – Damien Pirsy Dec 14 '11 at 13:53
I Used Parse_url for checking whether query exists in URI. Almost Worked..:) – Jenson M John Dec 14 '11 at 14:38

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

share|improve this answer
1  
Although This function is not meant to validate the given URL, it only breaks it up into the above listed parts. – Damien Pirsy Dec 14 '11 at 13:41
@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... – DaveRandom Dec 14 '11 at 13:43

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.