The easiest and fastest way to get the value of query string in PHP is through $_GET predefined variables. $_GET contains an associative array of variables passed to the current script via the URL parameters, which are passed through urldecode().
$_GET has the following syntax:
$_GET["name"]
Where name is the name of the variables contained inside query string of URL.
For example, in the URL of https://techjourney.net/?s=searchterms, the following PHP function will print out the “searchterms”.
<?php echo htmlspecialchars($_GET["s"]); ?>
DO NOT drop the htmlspecialchars() function to avoid malicious injection attack.
In another scenario, if you have to get the entire query string, uses the $_SERVER[‘QUERY_STRING’] predefined variables instead. For example, for same URL of https://techjourney.net/?s=searchterms, the following code will print “s=searchterms”.
<?php echo $_SERVER["QUERY_STRING"]; ?>
If you want to parse the URL and automatically transform all query parameters into corresponding PHP variables, parse_str() could help. For example, in the URL https://techjournye.net/?topic=search&s=keyword, the following code:
parse_str($_SERVER["QUERY_STRING"]);
Will create variables $topic and $s with values of “search” and “keyword” respectively. The following code will store all variables from query string in an array instead:
parse_str($_SERVER["QUERY_STRING"], $query_array);