Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking for null and missing query string parameters in PHP

I want to be able to distinguish between existing query string parameters set to null, and missing parameters. So the parts of the question are:

  • How do I check if a parameter exists in the query string
  • What's the established method for passing a null value in a query string? (e.g. param=null or param=(nothing) )

Thanks

like image 420
Yarin Avatar asked Dec 07 '10 23:12

Yarin


People also ask

How to check if query string is empty in PHP?

If you have a query string of query=string the value is "string" if you instead use: query=null the value will be "null" . Note that it is therefor a string. If you send: query= , the value will be "" or the empty string.

How do you get query parameters in php?

The parameters from a URL string can be retrieved in PHP using parse_url() and parse_str() functions. Note: Page URL and the parameters are separated by the ? character. parse_url() Function: The parse_url() function is used to return the components of a URL by parsing it.

What is PHP query string?

A query string is a term for adding/passing data in the URL. It is not language specific.


4 Answers

Use isset() and empty()

if (isset($_REQUEST['param'])) {   // param was set in the query string    if(empty($_REQUEST['param']))    {      // query string had param set to nothing ie ?param=&param2=something    } } 
like image 67
Byron Whitlock Avatar answered Sep 30 '22 07:09

Byron Whitlock


Or use array_key_exists:

if(array_key_exists("myParam", $_GET)) {  } 

I've never been keen on 'conventions' for passing empty values to the server - I'm used to testing for the presence of variables, and then trimming them and testing for emptiness, for example.

like image 31
karim79 Avatar answered Sep 30 '22 06:09

karim79


Values stored in $_GET and $_POST can only be strings or arrays, unless explicitly set at run-time. If you have a query string of query=string the value is "string" if you instead use: query=null the value will be "null". Note that it is therefor a string.

If you send: query=, the value will be "" or the empty string. Take note of the differences between isset and empty. isset will be true if the value is not null, whereas empty will be true when the value evaluates to false. Therefor "" will be true for both isset and empty.

If you just want to check if a query string parameter was set to the string value of "null", you can simply check $_GET['query']=='null' (you may want to adjust the case of the characters before the check)

like image 33
zzzzBov Avatar answered Sep 30 '22 06:09

zzzzBov


With one if statement instead of two:

if ((isset($_REQUEST['name'])) && (!empty($_REQUEST['name'])))
{
    $name= $_REQUEST['name'];
}
like image 41
MatthewK Avatar answered Sep 30 '22 07:09

MatthewK