Creating a Query String

To create a query string, you need to be able to URL encode the keys and values you want to include. Assume that we want to pass a URL to another page as part of a query string. The forward slashes and the colon in a full URL would create ambiguity for a parser. We must therefore convert the URL into hexadecimal characters. We can do this using PHP’s urlencode() function, which accepts a string and returns an encoded copy:

print urlencode("http://p24.corrosive.co.uk");
// prints http%3A%2F%2Fp24.corrosive.co.uk

Now that you can URL encode text, you can build your own query string. The following fragment builds a query string from two variables:

 <?php $interest = "arts"; $homepage = "http://p24.corrosive.co.uk"; $query ...

Get Sams Teach Yourself PHP in 24 Hours, Third Edition 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.