New in PHP 5 and quite promising is the Filter library of PECL code. Being developed by PHP’s creator and other major contributors, the future of Filter looks bright, even though it’s still in beta form (at the time of this writing). The Filter package provides two types of security:
◆ Data validation by type
◆ Data sanitization
What Filter offers is a unified interface for performing common types of validation and sanitization. For example, I might commonly use code like this:
if (is_numeric($_GET[‘id’])) {
$id = (int) $_GET[‘id’];
if ($id > 0) {
// Do whatever.
}
}
}
I could instead do this:
if ($id) { …
//Dow whatever.
}
To filter individual variables, there are two functions you’ll use: filter_input() and filter_var(). The first one is for working with variables coming from an outside source, like forms, cookies, sessions, and the server. The second is for variables within your own code. I’ll focus on filter_input()
here. Its syntax is:
$var = filter_input($variable_source,$variable_name, $filter, $options);
The sources, which the PHP manual calls “types,” are: INPUT_GET, INPUT_POST,
INPUT_COOKIE, INPUT_SERVER, INPUT_ENV, INPUT_SESSION, and INPUT_REQUEST. As you
can probably guess, each of these corresponds to a global variable ($_GET, $_POST, etc.). For example, if a page receives data in the URL, you’d use INPUT_GET (not $_GET). The second argument—the variable name—is the specific variable within the source that should be addressed. The $filter argument
indicates the filter to apply, using the constants as given below:
Constant name | Action
FILTER_VALIDATE_INT | Confirms an integer,optionally in a range
FILTER_VALIDATE_FLOAT | Confirms a float
FILTER_ VALIDATE_REGEXP | Matches a PCRE pattern
FILTER_ VALIDATE_URL | Matches a URL
FILTER_ VALIDATE_EMAIL | Matches an emailaddress
FILTER_SANITIZE_STRING | Strips tags
FILTER_SANITIZE_ENCODED | URL-encodes a string
This argument is optional, as a default filter will be used if none is pecified. Some filters also take options, like the FILTER_VALIDATE_INT in the
preceding example (which can take a range). The filter_input() function will return the filtered variable if the filtration or validation was successful, the Boolean FALSE if the filter didn’t apply to the data, or the value NULL
if the named variable didn’t exist in the given input. Thus you have multiple levels of validation in just one step.
- Kiran's blog
- 891 reads













Post new comment