Sams Teach Yourself HTML, CSS & JavaScript Web Publishing in One Hour a Day

(singke) #1
ptg16476052

670 LESSON 24: Taking Advantage of the Server



than a regular variable. Unfortunately, you have to give PHP a hint to let it know that
a field should be handled this way. (PHP has no idea what your form looks like; all it
knows about is the data that has been submitted.)
If you include [] at the end of the name of a form field, PHP knows that it should expect
multiple values for that field and converts the parameters into an array. This occurs even
if only one value is submitted for that field. Here’s an example:
<form action="postmultiplevalues.php" method="post">
<input type="checkbox" name="colors[]" value="red" /> Red<br />
<input type="checkbox" name="colors[]" value="green" /> Green<br />
<input type="checkbox" name="colors[]" value="blue" /> Blue
</form>

When the form is submitted, you can access the values as you would for any other
parameter, except that the value in the $_REQUEST array for this parameter will be an
array rather than a single value. You can access it like this:
$colors = $_REQUEST['colors'];
foreach ($colors as $color) {
echo "$color<br />\n";
}

If the user selects only one check box, the value will be placed in an array that has only
one element.

Exercise 24.1: Validating a Form


One of the most common tasks when it comes to server-side processing is form valida-
tion. When users submit data via a form, it should be validated on the server, even if your
page includes JavaScript validation, because you can’t guarantee that JavaScript valida-
tion was actually applied to the form data.
I use a simplified version of the user registration form from Lesson 12 in this exercise.
Figure 24.1 is a screenshot of the form I’ll be using. Here’s the HTML source:

Input ▼
<!DOCTYPE html>
<html>
<head>
<title>Registration Form</title>
</head>
<body>
▼ <h1>Registration Form</h1>
Free download pdf