When filtering user input data, you usually write your own methods to make judgments
For example, use regular expressions when verifying email addresses
$pattern = "/\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/"; if (!preg_match($pattern, $email)) { throw new \Exception(self::ERROR_PARAMETER_EMPTY . '_邮件格式有误:' . $email); }
If I don’t use regular expressions, is there any other simple method?
Use filter related functions
filter_has_var(type, variable) Whether there is a variable of the specified type.
filter_input Gets input from outside the script and filters it.
filter_input_array Gets multiple inputs from outside the script and filters them.
filter_var gets a variable and filters it.
filter_var_array Gets multiple variables and filters them.
filter_has_var
Determine whether the result of $_GET contains name
if(!filter_has_var(INPUT_GET, "name")) { echo("name 不存在"); } else { echo("name 存在"); }
filter_input
Look at an example of verifying the email address
if (!filter_input(INPUT_GET, 'email', FILTER_VALIDATE_EMAIL)) { echo "E-Mail is not valid"; } else { echo "E-Mail is valid"; }
filter_input_array
Filter the entire input source
$filters = array ( "name" => array ( "filter"=>FILTER_CALLBACK, "flags"=>FILTER_FORCE_ARRAY, "options"=>"ucwords" ), "age" => array ( "filter"=>FILTER_VALIDATE_INT, "options"=>array ( "min_range"=>1, "max_range"=>120 ) ), "email"=> FILTER_VALIDATE_EMAIL, ); print_r(filter_input_array(INPUT_POST, $filters));
filter_var,filter_var_array
No input source is required, filter the value directly
if(!filter_var("someone@example....com", FILTER_VALIDATE_EMAIL)) { echo("E-mail is not valid"); } else { echo("E-mail is valid"); }
The range of the input source
Verification
##Other filtering methods strip_tags deletes html tags
htmlentities Convert characters into HTML entities (it also escapes currency symbols such as euros, pounds, etc., copyright symbols, etc.)
htmlspecialchars function converts predefined characters into HTML entities.
The predefined characters are:
& (ampersand) becomes &
" (double quotation mark) becomes "
' (single quotation mark) becomes '
< (less than) becomes <
(greater than) becomes >
* Tip: To convert special HTML entities back to characters, use the htmlspecialcharsdecode() function.
$input = "<span>我是标题</span>"; echo htmlspecialchars($input) . "\n"; echo htmlentities($input) . "\n"; echo strip_tags($input) . "\n"; $input = "-- 'select * from "; echo addslashes($input) . "\n";