To get the query string from a URL in php, you can use $_GET super global to get specific key value pairs or $_SERVER super global to get the entire string.
// https://daztech.com/?key1=value1&key2=value2&key3=value3
echo $_GET['key1'];
echo $_GET['key2'];
echo $_SERVER['QUERY_STRING'];
//Output:
value1
value2
key1=value1&key2=value2&key3=value3
A query string is a part of a URL that assigns values to specified parameters. When building web pages, query strings help us pass and access information to be used on our web pages.
When working in php, the ability to easily access and work with query strings is important.
To get a query string from a URL, there are a few different ways you can get the key value pairs.
To get a specific parameter from a query string, you can use $_GET super global to access individual parameters from the query string by name.
// https://daztech.com/?key1=value1&key2=value2&key3=value3
echo $_GET['key1'];
//Output:
value1
If you want to get the entire query string, you can use the $_SERVER super global.
// https://daztech.com/?key1=value1&key2=value2&key3=value3
echo $_SERVER['QUERY_STRING'];
//Output:
key1=value1&key2=value2&key3=value3
After getting the entire query string, you can parse it for the key value pairs with the php parse_str() function.
Using $_GET to Get Query String Parameters in php
The $_GET super global variable allows us to get individual key value pairs from query strings.
There are a few additional cases which occur when using query strings that I want to share with you.
First, in a query string, you can have duplicate key names followed by square brackets. This will create a child array in $_GET for that key with numerically indexed values.
// https://daztech.com/?key[]=value1&key[]=value2&key[]=value3
echo $_GET['key'][0];
echo $_GET['key'][1];
echo $_GET['key'][2];
//Output:
value1
value2
value3
If the brackets are not empty, and have keys in them, then for a particular key, the child array belonging to the key will be an associative array.
// https://daztech.com/?key[ex1]=value1&key[ex2]=value2&key[ex3]=value3
echo $_GET['key']['ex1'];
echo $_GET['key']['ex2'];
echo $_GET['key']['ex3'];
//Output:
value1
value2
value3
Using $_SERVER to Get Query String in php
You can also use the $_SERVER super global variable to get the entire query string. After getting the query string, you can parse it with the php parse_str() function.
// https://daztech.com/?key1=value1&key2=value2&key3=value3
query_string = $_SERVER['QUERY_STRING'];
parse_str(query_string);
echo $key1;
echo $key2;
echo $key3;
//Output:
value1
value2
value3
Hopefully this article has been useful for you to learn how to get query strings and work with them in php.