ankitweblogic logo
W e b t u t o r i a l s

Define PHP

PHP Installation

PHP INI File

PHP Case Sensitivity

PHP Variable

PHP Echo & Print

PHP Operators

PHP Receiving Input

PHP Decision Making

PHP Loops

PHP Jumping Statement

PHP Image Gallery

PHP Arrays

PHP File Upload

PHP String Functions

PHP Math Functions

PHP Functions

PHP Variable Scope

PHP Constant Variable

PHP Superglobals

PHP Form Validation

PHP Include Statement

PHP Filter

PHP File Handling

PHP Date Functions

PHP Cookies

PHP Session

PHP Send Emails

PHP Captcha

PHP-MySQL Connectivity

PHP MySQL Select

PHP MySQL Insert

PHP MySQL Delete

PHP MySQL Update

PHP MySQL Injection

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.

The filter_var() function both validate and sanitize data.

Example: Sanitize a String

<?php
   $str = "<h1>Hello World!";
   $newstr = filter_var($str, FILTER_SANITIZE_STRING);
   echo $newstr;
?>

Validate an Integer

<?php
$age = 30;

if (filter_var($age, FILTER_VALIDATE_INT)) {
    echo("Integer is valid");
} else {
    echo("Integer is not valid");
}
?>

Note: To validate 0 value use
if (filter_var($age, FILTER_VALIDATE_INT) === 0 || !filter_var($age, FILTER_VALIDATE_INT) === false)

Example: 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");
}
?>

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");
}
?>

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");
}
?>

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 values can be "1", "true", "on", "yes", "0", "false", "off" and "no"

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";
}

?>