Use the built-in filter function of PHP for data validation, phpfilter

Source: Internet
Author: User

Use the built-in filter function of PHP for data validation, phpfilter

Use the filter function provided by PHP for data verification

PHP filters include two types
Validation:Used to verify that the verification item is valid
Sanitization:It is used to format the verified project. Therefore, it may modify the value of the verification item and delete invalid characters.
Refer to PHP official 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 has a unique ID. Each filter can be used by the filter_var () function. The following describes how to use it one by one. Note that the preceding string and strippedID are the same 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.

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

<?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' Options'Key array, as shown below:

<?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 code above and the page will not have any output, because the above returns False, Indicates that 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:

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

<?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.'<br />';    }?>

Run the above Code and output the following:

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

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

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

The following values return false.
0
"0"
"No"
"False"
"Off"
""
NULL
FALSE

The following operations are also supported:

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

<?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    /*** 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
float(1.234)Warning: filter_var() [function.filter-var]: decimal separator must be one char in /www/filter.php on line 13bool(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!<br />";    }?>

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-The URL must have a path 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 required 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    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!





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.