Parsing a URL querystring into variables in PHP

It’s common knowledge you can read variable from a URL querystring by using $_GET array in PHP, but that’s only possible if the URL is “executed” in the browser.

For those who might not know, querystrings are those variable-value pairs that appears behind ‘?’ of a URL. For example,

http://www.mysite.com/index.php?variable1=1&variable2=1

gives the querystring “variable1=1&variable2=1″.

What happens if you end up reading a URL from, say, a text file and you want to parse the querystring? In this case, the $_GET won’t work. So instead, PHP provides a function called parse_str(), which will convert the querystring into actual PHP variables within the scope of the code.

This is what happens when you use the function.

1
2
3
4
5
6
7
8
<?php
$myQryStr = "first=1&second=Z&third[]=5000&third[]=6000";
parse_str($myQryStr);
echo $first; //will output 1
echo $second; //will output Z
echo $third[0]; //will output 5000
echo $third[1]; //will output 6000
?>

As you can see, parse_str has converted the variable-value pairs, like “first=1″ into a PHP variable $first which has a value of 1, and so on.

In addition, parse_str can also take in an array as an optional second parameter like this:

1
2
3
4
5
6
7
8
<?php
$myQryStr = "first=1&second=Z&third[]=5000&third[]=6000";
parse_str($myQryStr, $myArray);
echo $myArray['first']; //will output 1
echo $myArray['second']; //will output Z
echo $myArray['third'][0]; //will output 5000
echo $myArray['third'][1]; //will output 6000
?>

The difference here is that the querystring variables are stored as keys within the array $myArray. Once it’s in an array, you can more easily manipulate and read the variables by cycling through the array.

On the flip side, you can do the opposite of parse_str by using the function call http_build_query().

Share and Enjoy:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • DZone
  • Propeller
  • Reddit
  • StumbleUpon
  • Technorati
  • Yahoo! Buzz
Posted on April 17, 2008 at 4:16 pm by Eldee · Permalink
In: PHP Tutorials · Tagged with: , ,

One Response

Subscribe to comments via RSS

  1. Written by Andreas M. Hahn on May 22, 2010 at 9:36 pm
    Permalink

    I recommend the use of “mb_parse_str” (PHP >= 4.0.6), which is actually a multi-byte safe way to parse query strings into arrays.

    You will find more best practices for parsing URLs as well as URIs, URNs and even IRIs according to RFC 3986 and RFC 3987 collected in a PHP class on this website:

    http://andreas-hahn.com/en/parse-url

Subscribe to comments via RSS

Leave a Reply