URL Querystrings
In
PHP the querystring in the
URL can be read with the global
$_GET variable.
The $_GET variable is an associative array where each querystring parameter is represented by a name and value.
So the url www.example.com/index.html?page=1&id=5 can be read like so..
echo $_GET["page"];
echo $_GET["id"];
This outputs
1 and
5 for page and id respectivley.
When creating a URL with querystring it is important to encode the variables as you can introduce characters
into a URL that are illegal and therefore will not allow the URL to work.
In PHP this is quite simple to do by using the
urlencode function as below...
$url = sprintf("http://www.example.com/index.html?page=%s&title=%s", urlencode($page), urlencode($page));
Because you are encoding the parameters you will need to decode the parameters once you recieve them with the
urldecode function.
In fact this is good general practice whenever you read a querystring, so...
echo urldecode($_GET["page"]);
echo urldecode($_GET["id"]);
Decoding the querystring parameters ensures any characters that have been escaped are unescaped.
No comments have been provided.
Written by Dominic Skinner
Last Updated: 2011-10-25 16:00:38