Working With Forms in PHP
Working With Forms
Forms are how your users talk to your scripts. To get the most out of PHP, you must master forms. The first thing you need to understand is that although PHP makes it easy to access form data, you must be careful of how you work with the data.
Security Measures: Forms Are Not Trustworthy
Your site's users can write their own form in HTML to use against your server; users can also bypass the browser entirely and use automatic tools to interact with web scripts. You should assume that people will mess around with parameters when you put a script on the Web, because they might be trying to discover an easier way to use your site (though they could be attempting something altogether less beneficial).
To ensure that your server is safe, you must verify all data that your scripts receive.
There are two approaches to checking form data: blacklisting and whitelisting.
Blacklisting is the process of trying to filter out all bad data by assuming that form submissions are valid and then explicitly seeking out bad data. In general, this technique is ineffective and inefficient. For example, let's say that you're trying to eliminate all "bad" characters from a string, such as quotes. You might search for and replace quotation marks, but the problem is that there will always be bad characters you didn't think of. In general, blacklisting assumes that most of the data you receive is friendly.
A better assumption to make about form data you're receiving is that it's inherently malicious; thus, you should filter your data in order to accept only valid data submissions. This technique is called whitelisting. For example, if a string should consist of only alphanumeric characters, then you can check it against a regular expression that matches only an entire string of A-Za-z0-9. Whitelisting may also include forcing data to a known range of values or changing the type of a value. Here is an overview of a few specific tactics:
$_FILES to Access Form Data
In Chapter 2, we showed you how to turn off the
register_globals setting that automatically sets global variables based on form data.
To shut down this dangerous setting, refer to "#14: Turning Off Registered Global Variables" on page 25. How do you use
$_GET to retrieve form data? Read on.