PHP | What is the purpose of data filtering in PHP?

|
| By Webner

Data Filtering is required in PHP to validate input and sanitize input received. Generally, we need to validate data before inputs need to be saved or used in our webpage. Wrong data inputs may cause exceptions or erroneous state in a webpage.

Data Filtering involves:
Validation: Determines whether input is valid or not.
Sanitization:  Removing illegal characters from input.

For example: filter_var, filter_input, filter_list are the filter functions for data filtering.

Let see few examples how filter functions can be used for data filtering

1. filter_var:

With filter_var, we can check the type of input and we can check that whether input is in correct form or not.

For example:

$email = ‘ishpreet.kaur@webners.com’;
if( !filter_var($email, FILTER_VALIDATE_EMAIL) === false)
	echo “valid email”;
else
	echo “invalid email”;

In the above example, we have checked whether email is in the correct format or not.

If there is some space appended at start or end of user input by mistake, then we can sanitize that input as follows:

$email = 'ishpreet.kaur@webners.com  ';
$email = filter_var($email,FILTER_SANITIZE_EMAIL);
if( !filter_var($email, FILTER_VALIDATE_EMAIL) === false)
echo "valid";
else
echo "invalid";

Similarly, we can validate other inputs using filter constants like: FILTER_VALIDATE_FLOAT for validating float numbers, FILTER_VALIDATE_URL for validating web address etc.

2.  filter_input:

With filter_input, one external variable can be checked against type. Form get or post user input can be validated with filter constants.

For example:

<form method="get" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
E-mail: <input type="text" name="email">
<input type="submit" name="submit" value="Submit">
</form>

<?php
if (!filter_input(INPUT_GET, "email", FILTER_VALIDATE_EMAIL) === false) {
echo("Email is valid");
} else {
echo("Email is not valid");
}
?>

In the above example, variable with name ‘email’ is specified in second parameter to be checked with filter constant mentioned in third parameter of filter function.

The general syntax for filter_input is:

filter_input(type, variable, filter)

Where input type to check for can be one of the following:
INPUT_GET, INPUT_POST, INPUT_COOKIE, INPUT_SERVER, INPUT_ENV

Leave a Reply

Your email address will not be published. Required fields are marked *