PHP Filters

PHP 5.2.0 & up has built-in validation functions just ready for you to use.

PHP Filters are an extension of PHP that help you to easily – and reliably – validate variables and strings

Filtering Variables
To use the filter extension to filter variables, you use the filter_var() function.
some examples.

Validate Integer

<?php
$variable = 1122;
echo filter_var($variable, FILTER_VALIDATE_INT);
?>

Validate Integer within range

<?php
$variable = 6;
$minimum_value = 5;
$maximum_value = 10;
echo filter_var($variable, FILTER_VALIDATE_INT, array("options" => array("min_range"=>$minimum_value, "max_range"=>$maximum_value)));
?>

Checking float values

<?php
$num = 31.53;
if(filter_var($num, FILTER_VALIDATE_FLOAT) === false){
echo $num." is not valid!";
}else{
echo $num." is a valid floating point number";
}
?>

Validate a URL

<?php
$url = "http://www.majolee.com/";
if(filter_var($url, FILTER_VALIDATE_URL) === FALSE){
echo $url." is not a valid URL";
}else{
echo $url." is a valid URL";
}
?>

Email address validation

<?php
$email = "marc@somehost.com";
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE){
echo $email." is invalid";
}else{
echo $email." is valid";
}
?>

Remove HTML tags from a string

<?php
$string = "<p>text</p>";
echo filter_var($string, FILTER_SANITIZE_STRING);
?>

Read previous post:
When uploading files, validate the file mime type

If you are expecting images, make sure the file you are receiving is an image or it might be a...

Close