PHP Filters


PHP Filters :– Validating data becomes important when your application starts to accept user input. Data validation is an integral part of working with forms. Not only can invalid submitted data lead to security problems, but it can also break your webpage. Today, we’ll take a look at how to remove illegal characters and validate data by using the “filter_var” function.

PHP filters are used to validate and sanitize external input.In earlier tutorial we have learnt about form validation how does it performed on user input to check them properly.
So one step ahead is to learn sanitization with validation which is more important because when beginners start validation scripting they would get some securities issues as well as SQL injection attacks.


PHP Filters | Example

The PHP filter extension has many of the functions needed for checking user input, and is designed to make data validation easier and quicker.

The filter_list() function can be used to list array of all supported filters.

We are explaining some best suitable examples and their outputs in screenshots for better understanding.

Example

<html>
<body>
<table>
<tr>
<td>Filter Name</td>
<td>Filter ID</td>
</tr>
<?Php

foreach(filter_list() as $id=>$filter){
	
	echo '<tr><td>'.$filter.'</td><td>'.filter_id($filter);
}
?>
</table>
</body>
</html>

PHP filter_var() Function

The filter_var() function filters a single variable with a specified filter.It takes two pieces of data:

    The variable you want to check

    The type of check to use

Sanitize a String

The following example uses the filter_var() function to remove all HTML tags from a string.

Example

<?Php
$str="<h1>Hello Tom</h1>";
echo $str;
$newstr=filter_var($str,FILTER_SANITIZE_STRING);
echo $newstr;
?>

Sanitize and Validate an Email Address

The following example uses the filter_var() function to first remove all illegal characters from the $email variable, then check if it is a valid email address:

Example

<?Php
$email="john.smithhotmail.com";
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
    echo "$email is a valid email address" ;
} else {
    echo "$email is not a valid email address";
}
?>

PHP Advanced Filters

Validate an Integer Within a Range

Example

<?php
$int = 499;
$min = 1;
$max = 500;

if (filter_var($int, FILTER_VALIDATE_INT, array("options" => array("min_range"=>$min, "max_range"=>$max))) === false) {
    echo("Variable value is not within the legal range");
} else {
    echo("Variable value is within the legal range");
}
?>

Advertisements

Add Comment

📖 Read More