Get URL query string parameters
Solution 1
$_SERVER['QUERY_STRING']
contains the data that you are looking for.
DOCUMENTATION
Solution 2
The PHP way to do it is using the function parse_url, which parses a URL and return its components. Including the query string.
Example:
$url = 'www.mysite.com/category/subcategory?myqueryhash';
echo parse_url($url, PHP_URL_QUERY); # output "myqueryhash"
Solution 3
The function parse_str()
automatically reads all query parameters into an array.
For example, if the URL is http://www.example.com/page.php?x=100&y=200
, the code
$queries = array();
parse_str($_SERVER['QUERY_STRING'], $queries);
will store parameters into the $queries
array ($queries['x']=100
, $queries['y']=200
).
Look at documentation of parse_str
EDIT
According to the PHP documentation, parse_str()
should only be used with a second parameter. Using parse_str($_SERVER['QUERY_STRING'])
on this URL will create variables $x
and $y
, which makes the code vulnerable to attacks such as http://www.example.com/page.php?authenticated=1
.
Solution 4
If you want the whole query string:
$_SERVER["QUERY_STRING"]
Solution 5
I will recommend the best answer as:
<?php
echo 'Hello ' . htmlspecialchars($_GET["name"]) . '!';
?>
Assuming the user entered http://example.com/?name=Hannes
The above example will output:
Hello Hannes!
enloz
Updated on September 21, 2021Comments
-
enloz over 2 years
What is the "less code needed" way to get parameters from a URL query string which is formatted like the following?
www.mysite.com/category/subcategory?myqueryhash
Output should be:
myqueryhash
I am aware of this approach:
www.mysite.com/category/subcategory?q=myquery <?php echo $_GET['q']; //Output: myquery ?>