Easy way to build GET query strings in php

Passing variables with a url is such a frequent thing programmers do that most of you may think this post is unwarranted. We call this method of passing variables as GET, the other being POST. It is one of those things which can be easily done in php. Lets take an example. You are to query a database and for that you need to send three variables via GET – city, id, paid.
The common way to pass them via GET is to construct a query string as below:

/* assume we want to pass this variables */
$city_name = "new york";
$invoice_id = 3456;
$paid = 1;
 
$query_string = "city={$city_name}&id={$invoice_id}&paid={$paid}";
$url = "http://www.example.com?" . $query_string;

The problem is that most php programmers get stuck using the above method. The method is fine for three to four variables, but for more than that the code gets hard to read and maintain, introducing subtle bugs in the constructed query.

The best way to pass GET variables is to use the http_build_query() function available from php version 5; which takes an array of variables and builds a nice URL encoded string which you can append to a url. And example is shown below.

$city_name = "new york";
$invoice_id = 3456;
$paid = 1;
 
$fields = array('city' => $city_name,
                'id' => $invoice_id,
                'paid' => $paid);
 
$url = "http://www.example.com?" . http_build_query($fields, '', "&");

In the above example the array contained the variable names and their values. You can also pass an array containing only values and let the function fill the variable name using the array index and a variable you supply (as a second parameter). For example if you want to pass an array of six cities than you can do the following, the second parameter of the function being the query variable.

$fields = array('paris',
                'new york',
                'florence',
                'london',
                'berlin',
                'delhi');
 
$url = "http://www.example.php?" .
        http_build_query($fields, 'city', "&");

The generated url will look like this:

http://www.example.php/?city0=paris&city1=new+york&city2=florence&city3=london&city4=berlin&city5=delhi

The third parameter to the function is not necessary as the function defaults to using ‘&’ as a separator. But I prefer making it explicit.
You can also easily pass a complex array as below:

$city_name      = "new york";
$invoice_id     = 3456;
$currency_name  = "euro";
$total          = 345;
$receipt_no     = "fgf44545";
 
$fields = array('city' => $city_name,
                'id' => $invoice_id,
                'paid' => array('currency' => $currency_name,
                                'amount' => $total,
                                'receipt' => $receipt_no)                
                );
 
$url = "http://www.example.php?" .
        http_build_query($fields, '', "&");

Which will create a url encoded query as following:

http://www.example.com?city=new+york&id=3456&paid%5Bcurrency%5D=euro&paid%5Bamount%5D=345&paid%5Breceipt%5D=fgf44545

To go the reverse way, we can parse the encoded url above using the code below:

$url_to_parse = "http://www.example.com?city=new+york&id=3456&paid%5Bcurrency%5D=euro&paid%5Bamount%5D=345&paid%5Breceipt%5D=fgf44545";
$parsed_url = parse_url($url_to_parse);
print_r($parsed_url);
 
/* This will output the following array */
Array
(
    [scheme] => http
    [host] => www.example.com
    [query] => city=new+york&id=3456&paid%5Bcurrency%5D=euro&paid%5Bamount%5D=345&paid%5Breceipt%5D=fgf44545
)

Now we can further parse the url query string stored in the ‘query’ variable above:

$url_query = $parsed_url['query'];
parse_str($url_query, $out);
print_r($out);
 
/* This will output the following array */
Array
(
    [city] => new york
    [id] => 3456
    [paid] => Array
        (
            [currency] => euro
            [amount] => 345
            [receipt] => fgf44545
        )
 
)

As can be seen the http_build_query() function really makes constructing GET queries simple.



12 thoughts on “Easy way to build GET query strings in php

  1. I’ve been doing PHP professionally for years and years and yet I’ve never seen this function before, not even mentioned anywhere or by anyone.

    What do we learn from this? That we all should re-read the PHP manual function list from time to time!

  2. Sorry, but it seems that the square brackets in the urls are filtered. I’ll use / instead of square bracket [
    ?opt=tpo&/foo\bar=1&foo/baz\=2

  3. I’ll use the example url from my post below:

    $url_to_parse = “http://www.example.com?city=new+york&id=3456&paid%5Bcurrency%5D=euro&paid%5Bamount%5D=345&paid%5Breceipt%5D=fgf44545″;

    $parsed_url = parse_url($url_to_parse);
    $url_query = $parsed_url[‘query’];

    parse_str($url_query, $out);
    print_r($out);

    This will print:
    Array
    (
    [city] => new york
    [id] => 3456
    [paid] => Array
    (
    [currency] => euro
    [amount] => 345
    [receipt] => fgf44545
    )

    )

    I’ve also updated the post above to include this comment.

  4. lol, the most interest in this article is the func “parse_str”
    it’s the first time I see it.
    shame on me :)

  5. I have a friend (with “hacker” in his name, no less) who I’ve told ten times this year about these functions, and still I catch him at it again and again and again.

    He actually LIKES doing it the hard way. Why?

    Worse, he makes up really novel schemes like using “$” to break up his variables, and writing custom parsers in pure php to parse his custom data notation.
    It doubles the size of some of his scripts.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>