Thursday, February 4, 2010

Recipe 8.6. Building a Query String










Recipe 8.6. Building a Query String



8.6.1. Problem


You


need to construct a link that includes name/value pairs in a query string.




8.6.2. Solution


Use the http_build_query( )
function, as in Example 8-14.


Building a query string



<?php
$vars = array('name' => 'Oscar the Grouch',
'color' => 'green',
'favorite_punctuation' => '#');
$query_string = http_build_query($vars);
$url = '/muppet/select.php?' . $query_string;
?>






8.6.3. Discussion


The URL built in Example 8-14 is:


/muppet/select.php?name=Oscar+the+Grouch&color=green&favorite_punctuation=%23



The query string has spaces encoded as

+. Special characters such as # are hex encoded as %23 because the ASCII value of # is 35, which is 23 in
hexadecimal.


Although the encoding that http_build_query( ) does prevents any special characters in the variable names or values from disrupting the constructed URL, you may have problems if your variable names begin with the names of HTML entities. Consider this partial URL for retrieving information about a stereo system:


/stereo.php?speakers=12&cdplayer=52&amp=10



The HTML entity for

ampersand (&) is &amp; so a browser may interpret that URL as:


/stereo.php?speakers=12&cdplayer=52&=10



To prevent embedded
entities from corrupting your URLs, you have three choices. The first is to choose variable names that can't be confused with entities, such as _amp instead of amp. The second is to convert characters with HTML entity equivalents to those entities before printing out the URL. Use
htmlentities( ):


$url = '/muppet/select.php?' . htmlentities($query_string);



The resulting URL is:


/muppet/select.php?name=Oscar+the+Grouch&amp;color=green&amp;favorite_punctuation=%23



Your third choice is to change the argument separator from & to &amp; by setting the configuration directive arg_separator.input to &amp;. Then, http_build_query( ) joins the different name=value pairs with &amp;:


/muppet/select.php?name=Oscar+the+Grouch&amp;color=green&amp;favorite_punctuation=%23





8.6.4. See Also


Documentation on http_build_query( ) at http://www.php.net/http_build_query and htmlentities( ) at http://www.php.net/htmlentities.













0 comments:

Post a Comment