FILTERS IN PHP

We use a filter in PHP to correct and clean the data. For correcting data, we check data is in correct form and there is not any invalid data. From cleaning data, we extract any character from the data which characters are not allowed in the data or we say that we remove malicious data from user input.

How filters work?

Firstly, we use PHP filter extension for describing the function of checking the input value was entered by the user.

In PHP several filter functions are defined:

  • filter_list()
  • filter_var()
  • filter_var_array()
  • filter_input()
  • filter_input_array()
  • filter_id()
  • filter_has_var()

PHP Code:

<p><b> Below table we describe filter name and filter id: </b></p>

<table>

<tr> <th> FILTER_NAME </th> <th> FILTER_ID </th>

<?php

foreach (filter_list() as $f_id =>$filter_name_id)
{
echo '<tr><td>' . $filter_name_id . '</td><td>' . filter_id($filter_name_id) . '</td></tr>';
}

?>

Result:

php-filter1

Now we describe a filter_var() function:

Filter_var() function is used for sanitizing a string & validating an integer. using filter_var() function we also check IP address, URL& Email_ID in a valid format & there is no any malicious data.

e.g.: PHP code

<?php

<title> PHP Filters </title>

// we check given value is integer or not.

// we enter an alphanumeric value...it is not an integer

$int_num = "ABC123";

// now using filter_var() function for checked the integer number

if (!filter_var($int_num, FILTER_VALIDATE_INT) === false)

{

echo "Correct: It is an integer";

}

else {

echo "Entered value is invalid. It is not an integer.";

}

?>

Result:

php-filter2

Now filter_var() function used for checking that email address is valid or not.

Php code:

<?php

// we know that valid email address format is abc@example.com

// but we enter & character instead of @.

$valid_email = 'john &example.com';

// extract  all malicious characters from email

$valid_email = filter_var($valid_email, FILTER_SANITIZE_EMAIL);

// check given email address is valid or not

if (!filter_var($valid_email, FILTER_VALIDATE_EMAIL) === false) {

echo "Entered $valid_email is valid email address";

} else {

echo "Entered $valid_email is invalid email address";

}

?>

Result:

php-filter3




Leave a Reply

avatar
  Subscribe  
Notify of