While working in PHP, eventually you’ll want to be able to pass a variable, or piece of data, from one page… to another page.
After all, the power of variables are obvious on a single page – allowing great type–saving and re–use capabilties. But the true power of variables is their ability to be transferred to a completely different page, so they can be used in even more situations.
GET it from the URL
The quickest (but most limited) way to transfer variables is by a method called GET. With GET, you append the variables onto the URL of the page you want the variables to be transferred to:
The example above would give the contact.php page two variables to utilize: id, and name, whose values are 301, and Matthom, respectively.
You can add as many variables to the URL as you’d like.
Beware – sometimes you don’t want your variables to be shown “out in the open.” Also, you are limited to 255 characters in the URL, so the variables can’t contain too much information.
From contact.php, you can GET these two variables via PHP:
# GRAB THE VARIABLES FROM THE URL
$id = $_GET['id'];
$name = $_GET['name'];
POST it from a FORM
Another way to transfer variables, and by far the more robust way, is to grab them from a form.
Let’s say this is your form field code:
These two input boxes allow users to enter information. At process.php, you can grab the variables in the same way:
# GRAB THE VARIABLES FROM THE FORM
$searchtype = $_POST['searchtype'];
$searchterm = $_POST['searchterm'];
Notice the use of
$_GET. This is an important distinction.
While using the POST method, there are no limitations on how many characters you can include. Also, the variables are not visible in the URL.