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.
refer to the official PHP documentation: Filter function Daquan
Reference Source: http://www.lai18.com/content/410997.html

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

<?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 the run code, it is found that there is no variable output, 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 originally wanted to add additional validation rules to your validation, you need to pass a Options' The array of keys, to the following:

<?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 ("options" = = Array ("Min_range" =& Gt $min, "max_range" = $max)));? >

Run the above code, the page will not have any output, because it returns false, stating 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 = n;    /*** lower limit of the int ***/    $min = ten;    /*** Validate the integer ***/    echo filter_var ($int, Filter_validate_int,array (' options ' = = Array (' Min_range ' =& Gt $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", a Rray ());    /*** 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); 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) C4/>[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
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 MA TCH ***/        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– The URL is required to 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 a URL to have a path 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– The required value is a valid IPv4 IP (e.g., 255.255.255.255)
Filter_flag_ipv6– The 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 an RFC-specified private domain IP (e.g. 192.168.0.1)
Filter_flag_no_res_range– The requirement value is not within 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 = "[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!





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.