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.

This site is a digital habitat of Sameer Borate, a freelance web developer working in PHP, MySQL and WordPress. I also provide web scraping services, website design and development and integration of various Open Source API's. Contact me at metapix[at]gmail.com for any new project requirements and price quotes.

12 Responses

1

Jani Hartikainen

November 13th, 2008 at 1:45 pm

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

blankyao

November 13th, 2008 at 4:42 pm

oh,I’ve never seen this function too.
thanks man.

3

Julien

November 14th, 2008 at 4:08 am

@Jani : It’s only available since PHP5, it’s kinda new.
Thanks for the tip.

4

Stoyan

November 14th, 2008 at 6:22 am

Is there an opposite function to http_build_query ?
A function that converts
http://xxxx.yyy?opt=tpo&foobar=1&foobaz=2
to
array(‘opt’ => ‘tpo’, foo => array(‘bar’ => 1, ‘baz’ => 2);

5

Stoyan

November 14th, 2008 at 6:24 am

In the previous post I meant:
http://xxxx.yyy?opt=tpo&foobar=1&foobaz=2

6

Stoyan

November 14th, 2008 at 6:26 am

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

sameer

November 14th, 2008 at 8:37 am

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.

8

Stoyan

November 15th, 2008 at 11:39 pm

Thanks for the great examples !!

9

Internet Marketing Email » Blog Archive » Easy way to build GET query strings in php : CodeDiesel

November 19th, 2008 at 6:42 pm

[...] Another fellow blogger put an intriguing blog post on Easy way to build GET query strings in php : CodeDieselHere’s a quick excerptI’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 … [...]

10

Pages tagged "easy"

November 20th, 2008 at 6:03 am

[...] bookmarks tagged easy Easy way to build GET query strings in php : CodeD… saved by 4 others     MaruMariMaru bookmarked on 11/20/08 | [...]

11

newhope

February 27th, 2009 at 12:28 am

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

12

SneakyWho_am_i

May 21st, 2009 at 2:32 am

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.

Your thoughts

Sign up for fresh content in your email