The method of checking data of filter function in PHP _php tips

Source: Internet
Author: User
Tags arrays rfc

Introduces the method of verifying data of filter function in PHP, the PHP filter contains two types:validation is used to verify that the verification item is legal
,sanitization is used to format the validated project, so it may modify the value of the validation entry to remove the illegal characters.

Input_filters_list ()

Used to list all the filters supported by the current system.

Copy 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 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 an ID of its own. Every filter here can be used by the Filter_var () function. The following describes how to use it. Note that the string and Strippedid are the same, because they are the same filter, or two aliases of the same filter.

Filter data

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

Copy 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 data an integer of 1234, because the $int variable through the integer type of validation, this time to change the contents of the $int variable

Copy Code code as follows:

<?php
/*** an integer to check ***/
$int = ' abc1234 ';

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

At this point the code is running and there is no output of any variables, because the $in variable does not pass validation, so this method returns bool (false). Also need to note that even if the $int= ", will return bool (FALSE)

Integer validation

The preceding sections of code simply verify the example of whether a given value is an integer. In fact, Filter_validate_int also provides a numerical range of validation, so let's verify a variable, determine whether 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 = m;

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

  /*** Validate the integer ***/
  echo filter_var ($int, Filter_validate_int, Array ("Min_range" => $min, "max_range" = > $max));
?>

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

Copy 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" => $min, "Max_range" => $max)) ;
?>

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

You can also use this method to verify the range of negative numbers
It also supports a single range of values, that is, to specify a range of maximum or minimum values, such as:

Copy 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 above code verifies that the $int is a value that is greater than (excluding equals) $min integer type, runs the code, and outputs 12

Validating a set of variables

The above examples are simply validating 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 do a simple example here:

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

Run the above code and the output is as follows:

Copy 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 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 Validation Filter_validate_boolean

Copy 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 that can return true

Copy Code code as follows:

1
"1"
"Yes"
"True"
"On"
TRUE

The following values will return False

Copy Code code as follows:

0
"0"
"No"
"False"
"Off"
“”
Null
FALSE

The following usage is also supported

Copy 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 was 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 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 validation 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 validation 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", arr Ay ());

  /*** 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) C5/>[4] => bool (false)
  [5] => bool (false)
  [6] => Array (0) {}
}

Floating-point filters enable us to specify a separator 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) c19/>{
    $out = Filter_var ($float, Filter_validate_float, Array ("Options" => Array ("decimal" => $dec _sep)); c21/>/*** dump the results ***/
    var_dump ($out);
>

In the code above, the first element in the $floats function has the value ', ' so that it is specified as ', ' when the value of 1,234 is judged, so returns true
Full return value of code above

Copy Code code as follows:

Float (1.234)
Warning:filter_var () [Function.filter-var]: Decimal separator must is 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, because of the uncertainty of the URL, it does not have the maximum length limit, and its format is diverse, you can read the RfC 1738来 to learn about the URL of some information. You can then create a class to validate all IPv4 and IPv6 URLs, and some other URL validation. 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 ***/
    echo "The URL, $url is valid!<br/>";
  }
? >

The above example 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-compliant URL. (For example:http://cg.am)
filter_flag_host_required– requires the URL to contain the host name (for example:http://levi.cg.com)
filter_flag_path_required– requires the URL to have a path after the host name (for example:http://levi.cg.am/test/phpmailer/)
filter_flag_query_required– requires a 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) c14/>{
    /*** If there is no match ***/
    echo "Sorry, $url are not valid!";
  }
  else
  {
    /*** if the URL is valid ***/
    echo ' The URL, $url is valid! ';
  }
? >

As you can see, the code above 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– requirement value is the private domain IP (such as 192.168.0.1) specified by RFC
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 user-defined functions to filter values.

This filter provides us with full 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 Code code as follows:

peter_is_a_great_guy!

The above mentioned is the entire content of this article, I hope you like.

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.