Friday, 13 July 2018

How To Get Key/Value Pair From URL Query String In PHP?

In this article we look at different ways in PHP to retrieve the query string and its parameter values from a URL. We'll be using the following string for all the examples in this article:
http://www.designcise.com/?key1=value1&key2=value2

Retrieving The Query String

Query String Of Current URL:

Using $_SERVER['QUERY_STRING'] in PHP we can get the full query string from the current URL. For example:
echo $_SERVER['QUERY_STRING']; 

// Output: key1=value1&key2=value2

Query String From A String

To retrieve the query string from a string we can use the parse_url function. For example:
echo parse_url('http://www.designcise.com/?key1=value1&key2=value2', PHP_URL_QUERY);

// Output: key1=value1&key2=value2

Query String Parameters As An Array

Using The $_GET Array:

Using $_GET array in PHP we can directly access any key/value pair in the current URL. For example:
echo $_GET['key1']; // Output: value1

Parsing A Query String

When we have all the key/value pairs in a single string, we can use the parse_strfunction to convert the key/value pairs to an array:
// method #1
parse_str($_SERVER['QUERY_STRING'], $output);

// method #2
parse_str(parse_url('http://www.designcise.com/?key1=value1&key2=value2', PHP_URL_QUERY), $output);
echo print_r($output, TRUE);

// Output: 
Array (
    ['key1'] => "value1"
    ['key2'] => "value2"
)

Handling Duplicate Keys In A Query String:

Using either of the two methods explained above, the output of duplicate keys in a query string would be a child array for that key with numerically indexed values. For demonstration purposes, consider the output of the following url:
http://www.designcise.com/?key[]=value1&key[]=value2

// Output: 
Array (
    ['key'] => Array (
        [0] => test1
        [1] => test2
    )
)

Things To Remember:

When using the methods explained above, remember the following are true:
  • Using $_GET would be the fastest way to access a key/value pair in the current url. Wherever possible, this should be the preferred choice.
  • Both parse_str and $_GET automatically urldecode values, which means any %## encoding is decoded in the given string. Plus symbols (i.e. +) are decoded to a space character. If this is not the behavior you're looking for, then you may use $_SERVER['QUERY_STRING'] to retrieve the entire query string in its original form or call urlencode on individual values.
  • Duplicate key names followed by square brackets (for example, ?key[]=value1&key[]=value2) create a child array for that key with numerically indexed values.

0 comments:

Post a Comment