There are 2 ways to pass variables in PHP: “
GET” and “
POST“. You might recognize these from the form tag (
<form method="GET">). What’s the difference?
GET passes the variables in the URL, and
POST passes the variables hidden. Ever get the error “resubmit POST data” when you click back on your browser? This is
POST in action: it is asking “do you want to send that hidden information again”.
You don’t need a form to send variables in PHP. Simply use
GET. The advantage to this is that you can save the data submitted to the page, because it is all in the URL:
varX is the name of the variable, then equals, then the value you want to assign to that variable. You put a “?” before the first, then separate the rest with “&”.
Now, you can retrieve them in PHP. Usually, you can just enter this:
Which will produce “value”
If globals for PHP are not enabled (which in PHP5 aren’t), you need to add a line:
$var1 = $_GET["var1"];
The site URL will look like: http://www.domain.com/index.php?id=5. The
id=5 is read by a PHP script. Usually, this id matches a row in a MySQL database that has all of the information for that page.
For PHP, POST data is usually sent from forms. First, you give a name to each of your
<input name="varname"> tags. For each of these, you use this line of code to retrieve (where
varname matches with the name of your input tag).
$varname = $_POST["varname"];
Do this for each input name, then you can use these variables in your script.
From now on, in PHP5 (and later in 6) you will have to add this line before you try to call the variable:
$variable = $_GET["variable"];
I should start playing a little with PHP6 these days. Just for fun.
Once a week or so we send an email with our best content. We never bug you, we just send you our latest piece of content.
If you found any value in this post, agree, disagree, or have anything to add - please do. I use comments as my #1 signal for what to write about. Read our comment policy before commenting! Comments such as "Thank you!", "Awesome!", "You're the man!" are either marked as spam or stripped from URL.