PHP Filter function to verify the data of the method, filter check _php tutorial

Source: Internet
Author: User
Tags rfc

In PHP, the filter function verifies the data in a detailed way, the filter check


This article introduces the method of validating data in PHP with filter function, and the PHP filter contains two types:validation is used to verify that the verification item is valid
,sanitization is used to format the validated item, so it may modify the value of the validation entry and remove the illegal characters.

Input_filters_list ()

Used to list all filters supported by the current system.

Copy the Code code as follows:
<?php
foreach (Filter_list () as $id = = $filter)
{
echo $filter. ' '. filter_id ($filter). " \ n ";
}
?>

The above code will output the following information

Filter Name filter Idint 257boolean 258float 259validate_regexp 272validate_url 273validate_email 274validate_ip 275string 513stripped 513encoded 514special_chars 515full_special_chars 522unsafe_raw 516email 517url 518number_int 519number_float 520magic_quotes 521callback 1024

Each filter will have a unique ID. Each of these filters can be used by the Filter_var () function. Here's how it will be used. Note that the above string and Strippedid are the same, because they are the same filter, or two aliases of the same filter.

Filtering data

Using the Filter_var () method to filter the data, here is a simple filter example

Copy the Code code as follows:
<?php
/*** an integer to check ***/
$int = 1234;
/*** Validate the integer ***/
Echo Filter_var ($int, filter_validate_int);
1234
?>

The above code will be the data of an integer type 1234, because the $int variable passes the validation of the integer type, this time change the contents of the $int variable

Copy the Code code as follows:
<?php
/*** an integer to check ***/
$int = ' abc1234 ';

/*** Validate the integer ***/
Echo Filter_var ($int, filter_validate_int);
?>

At this point in running the code, it is found that there is no output of the variable because the $in variable is not validated, so this method returns bool (false). It is also important to note that even $int= "returns BOOL (false)

Integer validation

The preceding sections of the code simply verify that a given value is an integer example. In fact Filter_validate_int also provides validation of the range of values, let's verify a variable, determine if it is an integer, and verify that its value is between 50 and 100

<?php  /*** An integer to check ***/  $int =;  /*** lower limit of the int ***/  $min =;  /*** upper limit of the int ***/  $max =;  /*** Validate the integer ***/  echo filter_var ($int, Filter_validate_int, Array ("Min_range" and $min, "max_range" = > $max));  42?>

Run the above code, found that 42 was output, and did not find any errors, this is why AH? When you want to add additional validation rules to validation, you need to pass an array containing the ' options ' key, as follows:

Copy the Code code as follows:
<?php
/*** an integer to check ***/
$int = 42;

/*** lower limit of the int ***/
$min = 50;

/*** upper limit of the int ***/
$max = 100;

/*** Validate the integer ***/
Echo Filter_var ($int, Filter_validate_int, Array ("options" = = Array ("Min_range" and "= $min," Max_range "and" = $max) ")) ;
?>

Run the above code, the page will not have any output, because the above returns false, indicating that the validation was successful.

This method can also be used to verify the range of negative numbers
This also supports single-range values, which specify only a maximum or minimum range, such as:
Copy the Code code as follows:
<?php
/*** an integer to check ***/
$int = 12;

/*** lower limit of the int ***/
$min = 10;

/*** Validate the integer ***/
Echo Filter_var ($int, Filter_validate_int,array (' options ' = = Array (' Min_range ' + $min)));
12
?>

The code above verifies that $int is greater than (not equal to) the value of an integer type $min, runs the code, and outputs 12

Validating a set of variables

The above examples simply validate a single value, so what if a set of variables is validated? The answer is to use Filter_var_array (). The function can validate multiple different types of data at the same time. Let's start with a simple example:

Copy the Code code as follows:
<?php
/*** an array of values to filter ***/
$arr = Array (ten, "109", "", " -1234", "some text", "Asdf234asdfgs", Array ());

/*** create an array of filtered values ***/
$filtered _array = Filter_var_array ($arr, filter_validate_int);

/*** Print out the results ***/
foreach ($filtered _array as $key = $value)
{
echo $key. '--$value. '
';
}
?>

Run the above code with the output as follows:

Copy the Code code as follows:
0--10
1--109
2--
3---1234
4--
5--
6--Array

Octal and hexadecimal

The Filter_validate_int filter supports both octal and hexadecimal, both of which are:

Filter_flag_allow_hex
Filter_flag_allow_octal
Passing Flags with arrays

Copy the Code code as follows:
<?php
/*** a hex value to check ***/
$hex = "0xFF";

/*** filter with HEX flag ***/
Echo Filter_var ($hex, Filter_validate_int, Array ("flags" = Filter_flag_allow_hex));
255
?>

BOOLEAN Authentication Filter_validate_boolean

Copy the Code code as follows:
<?php
/*** test for a Boolean value ***/
Echo Filter_var ("true", Filter_validate_boolean);
1
?>

The above code output 1, because the filter found a valid Boolean value, the following list of other values can return true

Copy the Code code as follows:
1
"1"
"Yes"
"True"
"On"
TRUE

The following values will return False

Copy the Code code as follows:
0
"0"
"No"
"False"
"Off"
“”
Null
FALSE

It also supports the following usage

Copy the Code code as follows:
<?php
/*** a simple array ***/
$array = Array (1,2,3,4,5);

/*** test for a Boolean value ***/
Echo Filter_var (In_array (3, $array), Filter_validate_boolean)? "TRUE": "FALSE";
True
?>

In the above code, we first judged that the In_array function executed successfully, and returned true, so the last code output true

We can also pass an array to determine the Boolean type of the values in the array

Copy the Code code as follows:
<?php
/*** a multi dimensional array ***/
$array = Array (0, 1, 2, 3, 4, array (0, 1, 2, 3, 4));

/*** Create the list of values ***/
$values = Filter_var ($array, Filter_validate_boolean, Filter_require_array);

/*** Dump the values ***/
Var_dump ($values);
?>

The above code output is as follows:

Array (6) {  [0] = = bool (false)  [1] = bool (true)  [2] = bool (false)  [3] = = BOOL (false)  [ 4] = = BOOL (false)  [5] = = Array (5) {    [0] = bool (false)    [1] = bool (true)    [2] = bool (false )    [3] = = BOOL (false)    [4] = = BOOL (false)  }}

Floating-point Verification filter_validate_float

<?php  /*** A FLOAT value to check ***/  $float = 22.42;  /*** validate with the FLOAT flag ***/  if (Filter_var ($float, filter_validate_float) = = = False)  {    echo "$ Float is not valid! ";  }  else  {    echo "$float is a valid floating point number";  }? >

Floating-point verification of arrays

As with other validations, you can also perform floating-point validation on an array. Similar to Boolean validation, provides a Flgs filter_require_array.

<?php  /*** An array of values ***/  $array = Array (1.2, "1.7", "", " -12345.678", "some text", "ABCD4.2EFGH", array ());  /*** Validate the array ***/  $validation _array = Filter_var ($array, Filter_validate_float, Filter_require_array); c4/>/*** dump the array of validated data ***/  var_dump ($validation _array);? >

The above code output is as follows

Array (7) {  [0] = = Float (1.2)  [1] = = Float (1.7)  [2] = = BOOL (false)  [3] = = Float (-23234.123)  [4] = = BOOL (false)  [5] = = BOOL (false)  [6] = = Array (0) {}}

Floating-point filters allow us to specify a delimiter between numbers

<?php  /*** An array of floats with seperators ***/  $floats = Array (    "1,234" = ",",    "1.234" and "=". . ",    " 1.2e3 "=", "  );  /*** validate the floats against the user defined decimal seperators ***/  foreach ($floats as $float = $dec _sep) 
  {    $out = Filter_var ($float, Filter_validate_float, Array ("options" = = Array ("decimal" = $dec _sep)));    /*** dump the results ***/    var_dump ($out);  }? >

In the above code, the first element in the $floats function has a value of ', ', so it is given a delimiter of ', ' when judging a value of 1,234, so it returns true.
The full return value of the above code

Copy the Code code as follows:
Float (1.234)
Warning:filter_var () [Function.filter-var]: decimal separator must be one char in/www/filter.php on line 13
BOOL (FALSE)
BOOL (FALSE)

Verify URL Filter_validate_url

URL validation is a very difficult behavior, due to the uncertainty of the URL, it does not have the maximum length limit, and its format is diverse, you can read the RfC 1738来 some information about the URL. You can then create a class to validate all IPv4 and IPv6 URLs, as well as validation of some other URLs. You can also simply use Filter_validate_url to verify the URL.

<?php   /*** A RFC compliant web address ***/  $url = "http://www.phpro.org";  /*** try to validate the URL ***/  if (Filter_var ($url, filter_validate_url) = = = FALSE)  {    /*** if there is no MA TCH ***/    echo "Sorry, $url is not valid!";  }  else  {    /*** if we match the pattern ***/    echo "The URL, $url is valid!
"; }? >

The example above uses a simple if statement to determine whether a given URL is legitimate, but not all URLs are in this format. Sometimes a URL can be an IP address, or it may pass multiple parameters in a URL. Here are a few flags to help us verify the URL:

The

filter_flag_scheme_required– requires that the URL be an RFC-compatible URL. (Example: http://cg.am )
Filter_flag_host_ required– requires the URL to contain the hostname (for example: http://levi.cg.com )
filter_flag_path_required– requires that the URL exist after the hostname (for example: http://levi.cg.am/test/phpmailer/ )
filter_flag_query_required– requires a query string for the URL (for example: http://levi.cg.am/?p=2618 )

<?php  /*** A non RFC compliant URL ***/  $url = "index.php";  /*** try to validate the URL ***/  if (Filter_var ($url, Filter_validate_url, filter_flag_scheme_required) = = = FALSE) c4/>{    /*** If there is no match ***/    echo "Sorry, $url was not valid!";  }  else  {    /*** if the URL is valid ***/    echo ' The URL, $url is valid! ';  }? >

It can be found that the above code does not pass validation

IP Filter Filter_validate_ip

The FILTER_VALIDATE_IP filter validates the value as an IP.
Name: "Validate_ip"
id-number:275

Possible flags:

filter_flag_ipv4– Required value is a valid IPv4 IP (e.g.: 255.255.255.255)
filter_flag_ipv6– Required value is a valid IPV6 IP (e.g.: 2001:0db8:85a3:08d3:1319:8a2e:0370:7334)
filter_flag_no_priv_range– Required value is the RFC-specified private domain IP (e.g. 192.168.0.1)
The filter_flag_no_res_range– requirement value is not in the reserved IP range. The flag accepts IPV4 and IPV6 values.
EMAIL Filter Filter_validate_email

The Filter_validate_email filter validates the value as an e-mail address.

<?php  $email = "Someone@exa mple.com";  if (!filter_var ($email, Filter_validate_email))  {    echo "e-mail is not valid";  }  else  {    echo "e-mail is valid";  }? >

Custom Filter Filter_callback

The Filter_callback filter uses a user-defined function to filter the values.

This filter provides us with complete control over the data filtering.

The specified function must be stored in an associative array named "Options".

<?php  $email = "Someone@exa mple.com";  if (!filter_var ($email, Filter_validate_email))  {    echo "e-mail is not valid";  }  else  {    echo "e-mail is valid";  }? >

Output

Copy the Code code as follows:
peter_is_a_great_guy!

The above is the whole content of this article, I hope you like it.

http://www.bkjia.com/PHPjc/1041332.html www.bkjia.com true http://www.bkjia.com/PHPjc/1041332.html techarticle in PHP, the filter function verifies the data in detail, the filter check describes the PHP filter function to verify the data of the method, the PHP filter contains two types: validation used to verify that the verification item is ...

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.