Use PHP's own filter function for data validation

Source: Internet
Author: User
Tags rfc

Use PHP's own filter function for data validation

PHP filters contain two types of
Validation: used to verify that a validation entry is valid
sanitization: used to format the validated item, so it may modify the value of the validation entry, remove the illegal character, and so on.

Input_filters_list ()

Used to list all filters supported by the current system.

<?phpforeach (Filter_list () as $id = + $filter) {echo $filter. ' '. filter_id ($filter). " \ n ";}?" >


The above code will output the following information
Filter Name
Filter ID
int
257
Boolean
258
Float
259
Validate_ RegExp
272
Validate_url
273
Validate_email
274
Validate_ip
275
String
513
Stripped
513
encoded
514
Special_chars
515
Full_special_chars
522
Unsafe_raw
516
Email
517
URL
518
number_int
519
Number_float
520
Magic_quotes
521
Callback
1024x768
Each filter will have a separate 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

<?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

<?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 = 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" =&G T    $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:

<?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)));? >


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:

<?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:

<?php/*** An array of values to filter ***/$arr = Array (ten, "109", "", " -1234", "some text", "Asdf234asdfgs", arr    Ay ());    /*** 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. '    <br/> '; }?>


Run the above code with the output as follows:

0--101--1092--3---12344--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

<?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

<?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
1
"1"
"Yes"
"True"
"On"
TRUE

The following values will return False
0
"0"
"No"
"False"
"Off"
“”
Null
FALSE

It also supports the following usage

<?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

<?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); /*** 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"  =>  ":",          "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

Float (1.234) Warning:filter_var () [Function.filter-var]: Decimal separator must is one char in/www/filter.php on line 13b Ool (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 match ***/         echo  "sorry,  $url  is not valid!";     }    else    {         /*** if we match the pattern ***/         echo  "the url,  $url  is valid!<br />";     }?> 


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:
filter_flag_scheme_required   – requires that the URL be an RFC-compatible URL. (For example: http://cg.am)
filter_flag_host_required   – requires that the URL contain a hostname (for example, http:// levi.cg.com)
filter_flag_path_required   – Requires the URL to have a path after the hostname (for example, http:// levi.cg.am/test/phpmailer/)
filter_flag_query_required   – Request URL There is 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!";     }?> 


can discover that the above code did not validate the value as an IP by validating the

IP filter filter_validate_ip

filter_validate_ip filter.

Name: "Validate_ip"

id-number:275

Possible flags:

Filter_flag_ipv4   – requires that the value is a valid IPv4 IP (e.g. 255.255.255.255)
Filter_flag_ipv6   – Required value is a valid IPV6 IP (for example: 2001:0db8:85a3:08d3:1319:8a2e:0370:7334)
filter_flag_no_priv_range   – requires that the value is a private domain IP specified by RFC (such as 192.168.0.1)
filter_flag_no_res_range   – The requirement value is not in the reserved IP range. The flag accepts IPV4 and IPV6 values.

Email filter filter_validate_email

Filter_validate_email Filter validates the value as an e-mail address.

<?php $email = "[email protected] 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 function Convertspace ($string) {return Str_replace ("", "_", $string);    } $string = "Peter is a great guy!"; Echo Filter_var ($string, Filter_callback,array ("Options" = "convertspace"));? >


Output

peter_is_a_great_guy!



PHP Filter function

Reference PHP official Documentation: filter function Daquan

Reference Source:
Use PHP's own filter function for data validation
Http://www.lai18.com/content/410997.html

Use PHP's own filter function for data validation

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.