Detailed description of the data verification method of the filter function in PHP, filter validation _ PHP Tutorial

Source: Internet
Author: User
In PHP, the filter function verifies data in detail. The methods for verifying data by using the filter function in PHP are described in detail. the methods for verifying data by using the filter function in PHP are described in detail. The PHP filter contains two types: validation is used to verify that the verification item is a detailed description of the methods used by the filter function to verify data in PHP.

Describes how to verify data using the filter function in PHP. The PHP filter contains two types:Validation is used to verify that the verification item is valid
,Sanitization is used to format the verified project, so it may modify the value of the verification item and delete invalid characters.

Input_filters_list ()

Used to list all filters supported by the current system.

The code is 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 has a unique ID. Each filter can beFilter_var ()Function usage. The following describes how to use it one by one. Note:String and strippedIDSame, because they are the same filter, or two aliases of the same filter.

Filter data

Use the filter_var () method to filter data. The following is a simple filtering example.

The code is as follows:
<? Php
/*** An integer to check ***/
$ Int = 1234;
/*** Validate the integer ***/
Echo filter_var ($ int, FILTER_VALIDATE_INT );
// 1234
?>

The code above will data an integer of 1234, because the $ int variable is verified by the integer type, this time change the content of the $ int variable

The code is as follows:
<? Php
/*** An integer to check ***/
$ Int = 'abc1234 ';

/*** Validate the integer ***/
Echo filter_var ($ int, FILTER_VALIDATE_INT );
?>

At this time, the code is running and no variable output is found. this is because the $ in variable is not verified, so this method returns bool (false ). Note that bool (false) is returned even if $ int =)

Integer verification

The above code simply verifies whether the given value is an integer. In fact, FILTER_VALIDATE_INT also provides a value range verification. next we will verify a variable, determine whether it is an integer, and verify whether its value is between 50 and 100.

<?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("min_range" => $min, "max_range" => $max));  //42?>

Running the code above, I found 42 was output, and no error was found. why? When you want to add a verification rule to the verification, you must pass an array containing the 'options' key as follows:

The code is 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" => $ min, "max_range" => $ max )));
?>

When you run the code above, no output is displayed on the page. if false is returned, the verification is successful.

This method can also be used to verify the range of negative numbers.
At the same time, this method also supports single-range values, that is, only specifying a maximum or minimum value range, such:
The code is 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 above code verifies whether $ int is an integer value greater than (not including equal to) $ min. run the code and output 12

Validate a group of variables

The above examples are just simple verification of a single value. what if we verify a group of variables? The answer is filter_var_array (). This function can verify multiple data types at the same time. Here is a simple example:

The code is as follows:
<? Php
/*** An array of values to filter ***/
$ Arr = array (10, "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 and output the following:

The code is 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. The two flags are:

FILTER_FLAG_ALLOW_HEX
FILTER_FLAG_ALLOW_OCTAL
Pass flags using arrays

The code is 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 verify FILTER_VALIDATE_BOOLEAN

The code is as follows:
<? Php
/*** Test for a boolean value ***/
Echo filter_var ("true", FILTER_VALIDATE_BOOLEAN );
// 1
?>

The above code outputs 1. because the filter finds a valid Boolean value, the following lists other values that can return true.

The code is as follows:
1
"1"
"Yes"
"True"
"On"
TRUE

The following values return false.

The code is as follows:
0
"0"
"No"
"False"
"Off"
""
NULL
FALSE

The following operations are also supported:

The code is 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, the in_array function is successfully executed, and true is returned. Therefore, the final code outputs true.

We can also pass an array to determine the boolean type of the value in the array.

The code is as follows:
<? Php
/*** A multi dimen1_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  /*** an 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";  }?>

Float array verification

Like other verifications, you can also perform floating point verification on an array. Similar to boolean verification, flgs FILTER_REQUIRE_ARRAY is provided.

<?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);  /*** 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) { }}

The floating point filter supports specifying a delimiter between numbers.

<?php  /*** an array of floats with seperators ***/  $floats = array(    "1,234" => ",",    "1.234" => "..",    "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 code above, the first element value in the $ floats function is ',', so it is specified with the separator ',' when determining the 1,234 value, so true is returned.
Complete return value of the above code

The code is 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 verification is very difficult. due to the uncertainty of the URL, there is no limit on the maximum length, and its format is diversified, you can read RFC 1738 to learn about the URL. Then you can create a class to verify all ipv4 and ipv6 URLs and 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 match ***/    echo "Sorry, $url is not valid!";  }  else  {    /*** if we match the pattern ***/    echo "The URL, $url is valid!
"; }?>

In the above example, a simple if statement is used to determine whether the given URL is legal, but not all URLs are in this format. Sometimes a URL can be an IP address, or multiple parameters may be passed in the URL. The following provides several flags to help us verify the URL:

FILTER_FLAG_SCHEME_REQUIRED-The URL must be RFC-compatible. (For example: http://cg.am)
FILTER_FLAG_HOST_REQUIRED-requires that the URL contain the host name (for example, the http://levi.cg.com)
FILTER_FLAG_PATH_REQUIRED-requires that the URL exist after the host name (for example, http://levi.cg.am/test/phpmailer)
FILTER_FLAG_QUERY_REQUIRED-requires the URL to have a query string (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)  {    /*** if there is no match ***/    echo "Sorry, $url is not valid!";  }  else  {    /*** if the URL is valid ***/    echo "The URL, $url is valid!";  }?>

It can be found that the above code has not passed verification

IP filter FILTER_VALIDATE_IP

The FILTER_VALIDATE_IP filter verifies the value as an IP address.
Name: "validate_ip"
ID-number: 275

Possible flag:

FILTER_FLAG_IPV4-the required value is a valid IPv4 IP address (for example, 255.255.255.255)
FILTER_FLAG_IPV6-the required value is a valid IPv6 IP address (for example, 2001: 0db8: 85a3: 08d3: 1319: 8a2e: 0370: 7334)
FILTER_FLAG_NO_PRIV_RANGE-the request value is the private domain IP address specified by RFC (for example, 192.168.0.1)
FILTER_FLAG_NO_RES_RANGE-the value is not within the reserved IP address range. This flag accepts IPV4 and IPV6 values.
Email Filter FILTER_VALIDATE_EMAIL

The FILTER_VALIDATE_EMAIL filter uses the value as the email address for verification.

<?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 user-defined functions to filter values.

This filter provides us with full control over data filtering.

The specified function must be stored in the associated 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

The code is as follows:
Peter_is_a_great_guy!

The above is all the content in this article. I hope you will like it.

Token describes how to verify data using the filter function in PHP. 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.