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

(singke) #1
ptg16476052

Processing Forms 669

24


Once you have access to the data the user submitted, you can do whatever you like with
it. You can validate it (even if you have JavaScript validation, you should still validate
user input on the server as well), store it in a database for later use, or send it to someone
via email.


Handling Parameters with Multiple Values


Most form fields are easy to deal with; they’re simple name and value pairs. If you have
a text field or radio button group, for example, you can access the value submitted using
$_REQUEST, like this:


$radio_value = $_REQUEST['radiofield'];
$text_value = $_REQUEST['textfield'];


However, some types of fields submit multiple name and value pairs—specifically check
boxes and multiple select lists. If you have a group of five check boxes on a form, that
field can actually submit up to five separate parameters, all of which have the same name
and different values. PHP handles this by converting the user input into an array rather


Preventing Cross-Site Scripting
You have to be careful when you display data entered by a user on a web page
because malicious users can include HTML tags and JavaScript in their input in an
attempt to trick other users who might view that information into doing something
they might not want to do, such as entering their password to your site and submit-
ting it to another site. This is known as a cross-site scripting attack.
To prevent malicious users from doing that sort of thing, PHP includes the
htmlspecialchars() function, which automatically encodes any special characters
in a string so that they are displayed on a page rather than letting the browser treat
them as markup. Or, if you prefer, you can use htmlentities(), which encodes all
the characters that are encoded by htmlspecialchars() plus any other characters
that can be represented as entities. In the preceding example, you re ally want to
write the script that displays the user’s name like this:
<p>Hello <?= htmlspecialchars($_POST['yourname']) ?>.
Thanks for visiting.</p>
That prevents the person who submitted the data from launching a successful cross-
site scripting attack.
If you prefer, you can also use the strip_tags() function, which just removes all
the HTML tags from a string.
Finally, if your form is submitted using the POST method, you should refer to the
parameters using $_POST rather than $_REQUEST, which also helps to avoid certain
types of attacks by ignoring information appended to the URL via the query string.
Free download pdf