Input filtering in PHP?
Is this link sufficent for example for input filtering form data? With a post for example?
<?php
$var=300;
$int_options = array(
"options"=>array
(
"min_range"=>0,
"max_range"=>256
)
);
if(!filter_var($var, FILTER_VALIDATE_INT, $int_options))
{
echo("Integer is not valid");
}
else
{
echo("Int开发者_Python百科eger is valid");
}
?>
What is the most common kind of filtering? Like sanitizing strings and numbers. I use preg_match for validation of email fields on the server side and regular expression checks in javascript. I'm no validation nazi but would like to have some sort of filtering for the most common things.
These kind of things I think I could abstract away in my application with some public static functions in a class for example, like this
Validate::String($str);
Validate::Interger($int);
What do you think about that?
filter_var() is a good start. If you are planning on using these inputs in any type of SQL statement, you should look into properly sanitizing it for that, too.
PDO with prepared statements, mysql_real_escape_string or any other db wrapper (MBD2, etc...) should provide this functionality for you.
I guess the key idea here is that there is a difference between filtering and sanitizing data, and there are different levels of doing each. It's very much a multi-part process.
For filtering, you could do a type check (is this an int?) and then validate that the input meets your criteria (is this int between 1 and 128?)
You'll also need to sanitize the data. htmlspecialchars for output, some proper quoting and escaping for use in SQL.
There is no common specification which say how to filter the user input. But using the built in functions is a very good starting point.
Date filtering is pretty common. For that I just use strtotime() and see if it comes out to a reasonable date (i.e. not 1969). Then the user can enter just about anything, including "+12 days".
Passwords are common, but a unique case. You may not want to allow spaces, must be a min length, contains letters and numbers, etc.
Data elements like social security number, phone and zip code you can be simple, must be a certain length and contain only numbers (U.S.). Or make them robust, make sure they are a valid format and within the "used" ranges. For example, a phone number can't start with 0.
Ideally one validation would use another. For example, zip code calling "only_digits" validation function first, then more detailed checking if valid.
精彩评论