Skip to content

Validations in PHP using validate filters

In the beginning of career i used to write regular expression or long lines of code for validating and sanitizing the user submitted data(Ex:come from an HTML form).But PHP > 5.2.x provides validation and sensitization filters which reduced lot of time and much easier to use.

From the manual : Validation & Sanitization
Validation is used to validate or check if the data meets certain qualifications. For example, passing in FILTER_VALIDATE_EMAIL will determine if the data is a valid email address, but will not change the data itself.

Sanitization will sanitize the data, so it may alter it by removing undesired characters. For example, passing in FILTER_SANITIZE_EMAIL will remove characters that are inappropriate for an email address to contain. That said, it does not validate the data.

Below are the examples for validating data using PHP’s Filter functions.

PHP Email Validation

$email = '[email protected]';
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo "This ($email) email address is considered valid.";
} else {
    echo "This ($email_a) is valid Email.";
}

The above example will output:

This ([email protected]) email address is considered valid.

PHP URL Validation

 $url = "https://arjunphp.com";
 if(filter_var($url, FILTER_VALIDATE_URL)) {
   echo "$url is valid URL";
  } else {
   echo "$url is invalid Valid URL";
  }

The above example will output:

https://arjunphp.com is valid URL

Validating IP addresses

$ip = '127.0.0.1';
if (filter_var($ip, FILTER_VALIDATE_IP)) {
    echo "This ($ip) IP address is considered valid.";
} else {
   echo "This ($ip) IP address is considered invalid.";
}

The above example will output:

This (127.0.0.1) IP address is considered valid.

You can get an list of all supported filters by calling PHP’s filter function called filter_list()


The above example will output something similar to:

Array
(
    [0] => int
    [1] => boolean
    [2] => float
    [3] => validate_regexp
    [4] => validate_url
    [5] => validate_email
    [6] => validate_ip
    [7] => validate_mac
    [8] => string
    [9] => stripped
    [10] => encoded
    [11] => special_chars
    [12] => full_special_chars
    [13] => unsafe_raw
    [14] => email
    [15] => url
    [16] => number_int
    [17] => number_float
    [18] => magic_quotes
    [19] => callback
)

That’s it.

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments