Retrieve & Get Query String from URL in PHP

Home»Software»Developer Tools»Retrieve & Get Query String from URL in PHP
A URL can pass along parameters in the form of query string. PHP can retrieve and get the query string for manipulation and handling in functions and processes.

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);
Tip
PHP’s parse_url() function also able to parses a URL and returns an associative array containing any of the various components of the URL that are present, including query string. You can specifically asks the parse_url() to return only the query string by specifying component parameter, i.e. “parse_url($url, PHP_URL_QUERY)”, or uses the key name “query” to get the query string value, i.e. “$parsed_url[’query’]”.

By |Categories: Developer Tools|Tags: |0 Comments

About the Author:

LK is a technology writer for Tech Journey with background of system and network administrator. He has be documenting his experiences in digital and technology world for over 15 years.Connect with LK through Tech Journey on Facebook, Twitter or Google+.

Pin It on Pinterest

Share This

Share This

Share this post with your friends!