8.8. Building a GET Query String

Problem

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

Solution

Encode the names and values with urlencode( ) and use join( ) to create the query string:

$vars = array('name' => 'Oscar the Grouch',
              'color' => 'green',
              'favorite_punctuation' => '#');
$safe_vars = array( );
foreach ($vars as $name => $value) {
    $safe_vars[ ] = urlencode($name).'='.urlencode($value);
}

$url = '/muppet/select.php?' . join('&',$safe_vars);

Discussion

The URL built in the solution 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 urlencode( ) 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 & 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 ...

Get PHP Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.