Check if parameters exist in an URL

32,648

Solution 1

You can use this simple function:

function url_get_param($url, $name) {
    parse_str(parse_url($url, PHP_URL_QUERY), $vars);
    return isset($vars[$name]) ? $vars[$name] : null;
}

See it in action here.

It will return the value of the parameter if it exists in the url, or null if it does not appear at all. You can differentiate between a parameter having no value and not appearing at all by the identical operator (triple equals, ===).

This will work with any URL you pass it, not just $_SERVER['REQUEST_URI'].

Update:

If you just want to know if there is any parameter at all in the URL then you can use some variant of the above (see Phil's suggestion in the comments).

Or, you can use the surprisingly simple test

if (strpos($url, '=')) {
    // has at least one param
}

We don't even need to bother to check for false here, as if an equals sign exists it won't be the first character.

Update #2: While the method using strpos will work for most URLs, it's not bulletproof and so should not be used if you don't know what kind of URL you are dealing with. As Steve Onzra correctly points out in the comments, URLs like

http://example.com/2012/11/report/cGFyYW1fd2l0aF9lcXVhbA==

are valid and yet do not contain any parameter.

Solution 2

Could also look for a specific key with array_key_exists(), e.g.

if(array_key_exists('some-key', $_GET))

http://php.net/manual/en/function.array-key-exists.php

Solution 3

Another way to check would be to use parse_url() method. Check docs here. This function will return an associative array with an element 'query' which will contain the GET parameters.

Use the empty() function to check and see whether this field is empty or not. If empty, then no parameters have been passed.

Code Sample -

<?php

    $url = "http://www.sub.domain.com/index.php?key=value&key2=value2";
    print_r(parse_url($url));
?>

Output

Array
(
    [scheme] => http
    [host] => www.sub.domain.com
    [path] => /index.php
    [query] => key=value&key2=value2
)
Share:
32,648
Run
Author by

Run

A cross-disciplinary full-stack web developer/designer.

Updated on March 08, 2020

Comments

  • Run
    Run about 4 years

    How can I check if an URL has parameters in it?

    for instance, if the string is like this,

    form_page_add.php?parent_id=1
    
    return true
    

    But if it is like this,

    form_page_add.php?
    
    return nothing
    

    Thanks.

    EDIT:

    Sorry for not being clear, the URL is submitted from a from as a string. and I will store that string in a variable,

    if(isset($_POST['cfg_path'])) $cfg_path = trim($_POST['cfg_path']);
    

    so I need to check this variable $cfg_path whether is has parameters in it.