Check if parameters exist in the url

How to check if the url has parameters in it?

for example, if the line is like this,

form_page_add.php?parent_id=1 return true 

But if so,

 form_page_add.php? return nothing 

Thanks.

EDIT:

Sorry for the ambiguity, the url is sent from line to line. and I will store this 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 has parameters in it.

+4
source share
4 answers

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 here in action .

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 distinguish a parameter that does not have a value and that does not appear at all with the identical operator (a triple is equal, === ).

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

Update:

If you just want to find out if there is any parameter at all in the URL, you can use one of the options above (see Phil's suggestion in the comments).

Or you can use a surprisingly simple test.

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

We don’t even have to worry to check false here, as if an equal sign existed, it would not be the first character.

Update # 2:. Although the strpos method will work for most URLs, it is not bulletproof and should therefore not be used unless you know which URL you are facing. As Steve Onzra correctly points out in the comments, URLs like

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

Valid and do not contain any parameters.

+18
source

You can also find a specific key using array_key_exists (), for example.

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

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

+25
source

Another way to check is to use the parse_url() method. Check out the docs here . This function will return an associative array with a request for an element that will contain GET parameters.

Use the empty() function to check if this field is empty or not. If empty, the parameters are not passed.

Code Example -

 <?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 ) 
+3
source

If you are looking to see if the URL is stored as a string (instead of the URL being called to call the PHP script), you can use strpos()

So, you could look for a string to appear ?, and then deal with it accordingly. For instance:

 $pos = strpos($myString, "?"); if($pos && $pos<strlen($myString){ //deal with URLs with parameters } 
0
source

Source: https://habr.com/ru/post/1344346/


All Articles