Extract Query String Parameters Using PHP parse_str
This article explains how to use the built-in PHP function
parse_str() to parse a query string into usable variables
or arrays. You will learn the correct syntax, view practical code
examples, and understand crucial security practices required for modern
PHP development when handling URL parameters.
What is parse_str() in PHP?
The parse_str() function is a native PHP function
designed to parse a query string—such as the portion of a URL after the
? character—and extract its key-value pairs. It
automatically handles URL-decoded characters, converting query
parameters into PHP variables or storing them inside an array.
Syntax and Parameters
The standard syntax for the function is:
parse_str(string $string, array &$result): void$string: The input query string to be parsed.$result: The output array where the parsed variables will be stored. This parameter is passed by reference.
Note: In older versions of PHP, the second parameter was optional, and the function would dynamically create global variables in the current scope. This behavior was deprecated in PHP 7.2 and completely removed in PHP 8.0. You must always provide the second argument to avoid fatal errors.
Code Example: Parsing a Query String into an Array
The most secure and modern way to use parse_str() is to
pass the output into a result array.
<?php
// A sample query string
$queryString = "genre=sci-fi&author=Arthur+C.+Clarke&published=1968";
// Parse the query string into the $params array
parse_str($queryString, $params);
// Access individual elements
echo $params['genre'] . "\n"; // Outputs: sci-fi
echo $params['author'] . "\n"; // Outputs: Arthur C. Clarke
echo $params['published'] . "\n"; // Outputs: 1968
// View the entire structured array
print_r($params);
/*
Output:
Array
(
[genre] => sci-fi
[author] => Arthur C. Clarke
[published] => 1968
)
*/
?>Handling URL-Encoded Data
The parse_str() function automatically decodes
URL-encoded characters. For example, a plus sign + or
%20 in the query string is automatically converted back to
a space character, as shown with “Arthur+C.+Clarke” becoming “Arthur C.
Clarke” in the example above.
Extracting Parameters from a Full URL
If you have a full URL rather than just the query string, you must
first extract the query component using parse_url() before
passing it to parse_str().
<?php
$url = "https://example.com/search?query=php+functions&category=tutorials";
// Extract the query component from the URL
$queryComponent = parse_url($url, PHP_URL_QUERY);
// Parse the query component
parse_str($queryComponent, $parsedData);
echo $parsedData['query']; // Outputs: php functions
echo $parsedData['category']; // Outputs: tutorials
?>