Reputation: 57286
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.
Upvotes: 4
Views: 33688
Reputation: 437774
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;
}
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.
Upvotes: 19
Reputation: 1874
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
)
Upvotes: 3
Reputation: 28187
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
Upvotes: 26
Reputation: 2923
If you are looking for whether a URL stored as a string (instead of the URL that is being called to invoke the PHP script), you can use strpos()
So you would be able to search the string for an occurence of ?, and then deal with it appropriately. For example:
$pos = strpos($myString, "?");
if($pos && $pos<strlen($myString){
//deal with URLs with parameters
}
Upvotes: 0