Page Stats
Visitor: 329
PHP Filter
PHP filters are used to validate and sanitize user input, and is designed to make data validation easier and quicker.
Validating data = Determine if the data is in proper form.
Sanitizing data = Remove any illegal character from the data.
PHP filter_var() function
The filter_var() function both validate and sanitize data.
Example 1: Sanitize a String
<?php $str = "<h1>Hello World!</h1>"; $newstr = filter_var($str, FILTER_SANITIZE_STRING); echo $newstr; ?>
Example 2: Validate an Integer
<?php $age = 30; if (filter_var($age, FILTER_VALIDATE_INT)) { echo("Integer is valid"); } else { echo("Integer is not valid"); } ?>
To validate 0 value use the following code:
if (filter_var($age, FILTER_VALIDATE_INT) === 0 || !filter_var($age, FILTER_VALIDATE_INT) === false)
Example 3: Validate integer value within a specified range.
<?php $int = 50; $min = 1; $max = 100; if (filter_var($int, FILTER_VALIDATE_INT, array("options" => array("min_range"=>$min, "max_range"=>$max))) === false) { echo("Value is not within the range"); } else { echo("Value is within the range"); } ?>
Example 4: Sanitize and Validate an Email Address
<?php $email = "name@gmail.com"; // Remove all illegal characters from email $email = filter_var($email, FILTER_SANITIZE_EMAIL); // Validate e-mail if (filter_var($email, FILTER_VALIDATE_EMAIL)) { echo("$email is a valid email address"); } else { echo("$email is not a valid email address"); } ?>
Example 5: Sanitize and Validate a URL
<?php $url = "http://www.website.com"; // Remove all illegal characters from a url $url = filter_var($url, FILTER_SANITIZE_URL); // Validate url if (filter_var($url, FILTER_VALIDATE_URL)) { echo("$url is a valid URL"); } else { echo("$url is not a valid URL"); } ?>
Example 6: PHP FILTER_VALIDATE_BOOLEAN Filter
<?php $var="yes"; if(filter_var($var, FILTER_VALIDATE_BOOLEAN)){ echo "Boolean Value is Valid"; } else{ echo "Boolean Value is NOT Valid"; } ?> //Possible return values can be "1", "true", "on", "yes", "0", "false", "off" and "no"
Example 7: PHP Float Validate
<?php $var=10.5; if(filter_var($var, FILTER_VALIDATE_FLOAT)){ echo "Float Value is Valid"; } else{ echo "Float Value is NOT Valid"; } ?>