Page 307 - Beginning PHP 5.3
P. 307
Chapter 10: Preserving State With Query Strings
$firstName = “John”;
$age = “34”;
$queryString = “firstName=$firstName & amp;age=$age”;
echo ‘ < p > < a href=”moreinfo.php?’ . $queryString . ‘” > Find out more info on
this person < /a > < /p > ’;
This code generates the following markup:
< p > < a href= “ moreinfo.php?firstName=John & amp;age=34 “ > Find out more info on
this person < /a > < /p >
If the user then clicks this link, moreinfo.php is run, and the query string data
( firstName=John & age=34 ) is passed to the moreinfo.php script. Data has been transmitted from one
script execution to the next.
Note that the ampersand ( & ) character needs to be encoded as & amp; inside XHTML markup.
One thing to watch out for is the type of characters that you insert into the field names and values in
your query string. The specifications for a query string allows only the following characters to be used
within field names and values: letters, numbers, and the symbols - , _ , . (period), ! , ~ , * , ‘ (single quote),
( , and ) .
So what do you do if you need to transmit other characters, such as spaces, curly braces, or ? characters?
The answer is that you should use URL encoding . This is a scheme that encodes any reserved characters
as hexadecimal numbers preceded by a percent ( % ) symbol, with the exception of space characters, which
are encoded as plus ( + ) signs. (Characters that don ’ t need to be encoded, such as letters and numbers, are
sent as they are.)
As it happens, PHP gives you a function called urlencode() that can encode any string using URL
encoding. Simply pass it a string to encode, and it returns the encoded string. So you can use
urlencode() to encode any data that may contain reserved characters. Here ’ s an example:
$firstName = ”John”;
$homePage = ”http://www.example.com/”;
$favoriteSport = ”Ice Hockey”;
$queryString = “firstName=” . urlencode( $firstName ) . “ & amp;homePage=” .
urlencode( $homePage ) . “ & amp;favoriteSport=” . urlencode( $favoriteSport );
echo ‘ < p > < a href=”moreinfo.php?’ . $queryString . ‘” > Find out more info on
this person < /a > < /p > ’;
This code snippet outputs the following markup:
< p > < a href=”moreinfo.php?firstName=John & amp;homePage=http%3A%2F%2Fwww.example.
com%2F & amp;favoriteSport=Ice+Hockey” > Find out more info on this person < /a > < /p >
If you ever need to decode a URL - encoded string you can use the corresponding urldecode() func-
tion. See http://www.php.net/urldecode for details.
269
c10.indd 269
c10.indd 269 9/21/09 9:05:08 AM
9/21/09 9:05:08 AM