Search code examples
phpurlquery-stringurl-validation

URL with query string validation using PHP


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.


Solution

  • 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.