PHP Web Fundamentals
Building a Query String
Problem
You need to construct a link that includes name/value pairs in a query string.Solution
Use the http_build_query() function:$vars = array('name' => 'Oscar the Grouch',
'color' => 'green',
'favorite_punctuation' => '#');
$query_string = http_build_query($vars);
$url = '/muppet/select.php?' . $query_string;
Discussion
The URL built in the Solution is:/muppet/select.php?name=Oscar+the+Grouch&color=green&favorite_punctuation=%23
Because only some characters are valid in URLs and query strings, the function has encoded the data into the proper format. For example, this query string has spaces 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&=10
The HTML entity for ampersand (&) is & 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&color=green&favorite_punctuation=%23
Your third choice is to change the argument separator from & to & by setting the configuration directive arg_separator.input to &. Then, http_build_query() joins the different name/value pairs with &:
ini_set('arg_separator.input', '&');
No comments:
Post a Comment