PHP Variables and Web Forms
July 21, 2000
One of the more popular uses of server-side scripts is to process form
submissions from web pages. PHP makes it especially easy to bring the
values from form fields into your PHP code. Let's take a simple HTML
form, a single-line text field where a visitor can enter their e-mail
address, as coded in HTML:
<FORM action="process.php3" method="get">
Please enter your e-mail address:
<INPUT type="text" size=20 name="email">
<BR><INPUT type="submit">
</FORM>
When the above form is submitted, a parameter named "email" with
whatever value the user entered will be submitted to the PHP script
process.php3. Within that script, a variable named $email
will automatically be created with the value from the form:
process.php3:
<?php
print "Your address, $email, has been added to our mailing list.";
addToMaillist($email);
?>
Note that addToMaillist is a fictional function, that we might
have created to place the user's email address into a text file
somewhere.
Because PHP migrates form field names into variables, you may wish to
construct form field names with an eye towards their resulting data
structure in PHP. For instance, suppose you have one form that asks
for information about a recipient of some sort. You may want to contain
that form's values inside a $recipient array, for example, to
improve data management inside your PHP script:
<FORM action="process.php3" method="get">
Please enter the recipient's e-mail address:
<INPUT type="text" size=20 name="recipient[email]"><BR>
Please enter the recipient's full name:
<INPUT type="text" size=20 name="recipient[name]"><BR>
<BR><INPUT type="submit">
</FORM>
process.php3:
<?php
while (list($key,$value) = each($recipient)) {
print "$key: $value<BR>";
}
?>
The HTML form above was migrated into a PHP array named
$recipient with the keys email and name. Above,
our PHP code simply reproduces the loop we saw earlier and outputs
each key and value in this array, for instance (depending on what we
submitted in the form):
email: cat@doglover.net
name: Mrs. Kitty
Data collection: Arrays
Welcome to PHP
Operations and Comparisons
|