I originally created this page while I was trying to learn a thing or two about PHP. Since then I’ve become a .NET programmer and don’t do much with PHP. However, I’m always trying to learn new things.
Here we discuss two arrays of data that are available to PHP that allow you to get information from the query string or from a form submission on your website. They are the _GET and the _POST arrays. The _GET array contains key-value pairs for the information passed in on the query string, and the _POST array contains information submitted via a form post to your page.
Here are some examples on how to get values from the _GET or _POST arrays.
Parsing the Query String
For the true newbies (I’m guessing there’s a few reading this page), the Query String is the information that is appended to a page name when making a page request.
For Example, in the URL:
http://www.tomasvera.com/header_test.php?key1=value1&key2=value2
the italic text is the query string. Here’s a link to a Wikipedia entry on the topic: http://en.wikipedia.org/wiki/Query_string
Let’s run through an example that will reload this page and allow you to see this in action. Click the following link. This will re-load this page and show the values of the keys in the query string.
http://www.tomasvera.com/programming/getting-request-variables-in-php/?key2=value2&favorite_food=pizza&testsubmit=true.
The information passed in the query string is available as a set of Key-Value pairs. So in this example I simply iterate over the collection of key-value pairs and echo their values to the screen. If you want to look at a specific item in the collection, you can retrieve it by name as is shown in the next section.
Getting a Specific Value
To get the value of a specific key that you want, you can simply use syntax such as
echo($_GET["key_name"]); -- or -- echo($_POST["key_name2"]);
Fill in and submit the following form. We can then see the value of the “favorite_food” input. Don’t worry, nothing gets stored, it is just sample data. (NOTE: The page will re-load when you submit the form)
So… you’ve read this far. That means you’re either pretty easily amused, or you are actually curious about this. Hopefully, you will find this useful.
If you have any questions about this page, or any of the code used to create this page, just let me know.