PHP parse_str() Function

PHP

PHP parse_str() - Parse Query String

The parse_str() function in PHP is a powerful tool designed to parse URL query strings into variables or arrays. Whether you need to convert GET parameters into usable PHP variables or work with URL encoding data, this function simplifies the process of extracting key-value pairs from query strings.

Prerequisites

  • Basic understanding of PHP syntax and variables.
  • Basic knowledge of URL query strings and GET parameters.
  • PHP environment setup (PHP 5.0+ recommended).
  • Familiarity with arrays in PHP is a plus.

Setup Steps

To start using parse_str(), follow these setup steps:

  1. Ensure you have access to a working PHP environment (e.g., local server with XAMPP, LAMP, MAMP, or remote server).
  2. Create a PHP file (e.g., parse_str-demo.php) to test code examples.
  3. Optionally, familiarize yourself with URL query strings by analyzing URLs like:
    https://example.com/page.php?name=John&age=25&city=New+York

What is PHP parse_str()?

The parse_str() function parses the query string passed to it, converting it into variables in the current scope or an associative array. Its signature is:

void parse_str ( string $string [, array &$arr ] )
  • $string: The input query string to parse (e.g., name=John&age=25).
  • $arr (optional): If provided, the function stores the parsed parameters into this array instead of creating variables.

Basic Example – Parsing into Variables

This example parses a query string and creates individual variables in the current scope.

<?php
$query = "name=John&age=25&city=New+York";
parse_str($query);

echo "Name: $name\n";  // John
echo "Age: $age\n";    // 25
echo "City: $city\n";  // New York
?>

Here, parse_str() creates variables $name, $age, and $city with the corresponding values.

Parsing into an Array

To avoid creating variables directly (which could overwrite existing ones), use the second argument to store the result into an array:

<?php
$query = "name=John&age=25&city=New+York";
parse_str($query, $output);

print_r($output);
/* Output:
Array
(
    [name] => John
    [age] => 25
    [city] => New York
)
*/
?>

Now all parameters reside in the $output array safely without polluting the global scope.

Handling Nested Query Strings

PHP parse_str() also supports parsing nested arrays from query strings.

<?php
$query = "user[name]=John&user[age]=25&user[address][city]=New+York&user[address][zip]=10001";
parse_str($query, $data);

print_r($data);
/* Output:
Array
(
    [user] => Array
        (
            [name] => John
            [age] => 25
            [address] => Array
                (
                    [city] => New York
                    [zip] => 10001
                )
        )
)
*/
?>

The function intelligently converts string-based nested keys into multidimensional arrays, useful for complex GET data.

Best Practices

  • Prefer Array Output: Always use the optional second argument to parse into an array rather than creating variables dynamically for better code maintainability and security.
  • Validate Input Data: Query strings can be manipulated by users; always sanitize and validate to prevent security risks such as injection or variable overwrite.
  • Use Built-in PHP Superglobals: When dealing with actual URL parameters, consider using $_GET unless you specifically need to parse custom query strings.
  • URL Decode Before Processing: If necessary, use urldecode() for raw input strings before parsing.

Common Mistakes

  • Not Using Second Argument: Relying on creating variables dynamically can unintentionally overwrite existing variables, creating bugs or security risks.
  • Passing Incomplete Query Strings: Partial or malformed query strings may result in unexpected outputs or no variables.
  • Misunderstanding URL Encoding: Forgetting that query strings are URL encoded can lead to incorrectly parsed values.
  • Assuming Data Types: All parsed values are strings by default; explicit casting may be necessary.

Interview Questions

Junior-Level Questions

  • Q1: What does parse_str() function do in PHP?
    A: It parses a query string into variables or an array.
  • Q2: What type of input does parse_str() expect?
    A: A URL-encoded query string like "key=value&key2=value2".
  • Q3: How do you prevent parse_str() from creating variables in the current scope?
    A: Use the second argument to store parsed data into an array.
  • Q4: Does parse_str() decode URL-encoded characters?
    A: Yes, it automatically decodes them.
  • Q5: Can parse_str() handle nested query string parameters?
    A: Yes, it converts them into multidimensional arrays.

Mid-Level Questions

  • Q1: What are the security implications of using parse_str() without the second argument?
    A: It can overwrite existing variables, potentially causing security risks.
  • Q2: How would you safely parse a query string in PHP to avoid polluting global scope?
    A: By passing a second argument array to store the parsed result.
  • Q3: What is the difference between $_GET and parse_str()?
    A: $_GET automatically holds URL GET parameters, whereas parse_str() parses any string manually.
  • Q4: How does parse_str() handle duplicate keys in a query string?
    A: It overwrites previous occurrences with the latest value.
  • Q5: Can parse_str() parse query strings that contain array-like syntax? Give an example.
    A: Yes, e.g. items[]=apple&items[]=banana becomes $items = ['apple', 'banana'].

Senior-Level Questions

  • Q1: How would you implement input validation after parsing a query string with parse_str()?
    A: Sanitize each array element or variable after parsing, using filters or validation functions such as filter_var().
  • Q2: Discuss scenarios where using parse_str() is preferred over directly accessing $_GET.
    A: When parsing custom query strings not passed via URL, or processing query data from other sources like POST bodies or API calls.
  • Q3: How does parse_str() internally handle URL encoding and decoding in nested keys?
    A: It decodes keys and values, then interprets array syntax (square brackets) to build nested arrays recursively.
  • Q4: Can parse_str() be exploited for variable injection? How to mitigate?
    A: Yes, if used without the second argument, attackers can overwrite critical variables. Use array output and whitelist keys.
  • Q5: How would you extend or wrap parse_str() to provide type casting after parsing?
    A: Write a wrapper function that calls parse_str() and then iterates through the array to cast values based on expected types.

Frequently Asked Questions (FAQ)

Q: Can parse_str() parse query strings with spaces and special characters?
A: Yes, it automatically decodes URL-encoded characters like '+' to space and '%20' to space.
Q: What happens if I call parse_str() on an empty string?
A: No variables or array elements are created; it essentially does nothing.
Q: Is it safe to use parse_str() with user input?
A: Only if you store parsed data in an array and properly validate or sanitize before using.
Q: Can parse_str() parse strings that are not URL query strings?
A: It expects key=value pairs joined by & or ; and will try to parse any such string, but results may be unpredictable for non-query string inputs.
Q: Does parse_str() work with PHP versions before 5.0?
A: No, it is available from PHP 4, but the accepted standard syntax and behavior are consistent from PHP 5 onwards.

Conclusion

The PHP parse_str() function is a versatile and easy-to-use tool for converting URL query strings into PHP variables or arrays. Properly using its optional array argument can prevent security vulnerabilities and potential bugs caused by global variable injection. It's especially useful when working with GET parameters, custom query strings, or nested URL data structures. Follow best practices by validating and sanitizing parsed data, and understanding how the function parses complex nested strings will allow you to efficiently handle URL parameters in your PHP applications.