Using the query string in PHP
This article tells you how to pass variables to a PHP page using the query string, and how to access them from that page.
Have you ever seen a URL which looked like
www.example.com/page.php?mode=1&style=red? Well, this page is being passed variables and their values through the query string, here the variables
style are being passed, with values
red respectively. The question mark
? indicates the start of the query string and the ampersand,
&, symbol seperates variable=value assignments. The page is then able to read these variables and react according to them, for example to display them to the user.
Passing a query string to a page
There are two ways to pass a query string to a page, the first is to enter it manually, for example:
The above HTML creates a link to a page passing the variable
mode with the value
An alternative, and perhaps more useful, way is to use HTML forms. The main thing to remember with forms is that you need to use the GET method to send information via the query string, for example:
This code displays a simple HTML form with a text box and a submit button. When the user enters their name and presses submit, the information in the name box is passed to a page called “page.php” (specified in the form’s action attribute) via the query string. So, if I entered
moose and pressed submit, the form will call
page.php?username=moose. Remember that
username was what we entered as the text input’s name attribute.
Accessing a query string element in a PHP page
In PHP, all the information passed via the query string is held in the
$_GET super global array (prior to PHP version 4.1.0 it was called
$HTTP_GET_VARS, but that’s now depreciated). To access an item, type
$_GET['varName'], where varName is the name of the variable in the query string.
To demonstrate, let’s create page.php to process the information from the form above:
So now, me typing in moose and pressing submit will generate the reply “Hello, moose”.
Listing the contents of $_GET
Should you wish to find out everything that’s in the query string, you can do so with the following code which displays the variables next to their values in a table:
This article showed you how to pass information between pages with the query string, and a use which allows you to add some increased interactivity. There are a lot of other uses, for example selecting which section of a site to display based on a variable in the query string, and processing form data.