Open In App

PHP Filter and Filter Constant

PHP Filter is an extension that filters the data by either sanitizing or validating it. It plays a crucial role in the security of a website, especially useful when the data originates from unknown or foreign sources, like user-supplied input. For example data from an HTML form

There are mainly two types of filters which are listed below:



Example 1: PHP program to validate URL using FILTER_VALIDATE_URL filter. 




<?php
// PHP program to validate URL
 
// Declare variable and initialize it to URL
 
// Use filter function to validate URL
if (filter_var($url, FILTER_VALIDATE_URL)) {
    echo "valid URL";
} else {
    echo "Invalid URL";
}
 
?>

Example 2: PHP program to validate email using FILTER_VALIDATE_EMAIL filter. 






<?php
// PHP program to validate email
 
// Declare variable and initialize it to email
$email = "xyz@gmail.com";
 
// Use filter function to validate email
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo "Valid Email";
} else {
    echo "Invalid Email";
}
 
?>

Example 3: PHP program to sanitize email using FILTER_SANITIZE _EMAIL filter. 




<?php
// PHP program to sanitize an email
 
// Declare variable and initialize it
// to an email with illegal characters
$email = "user@geeksforgeeks.org";
 
// Sanitize the email using the FILTER_SANITIZE_EMAIL filter
$sanitizedEmail = filter_var($email, FILTER_SANITIZE_EMAIL);
 
// Output the sanitized email
echo "Sanitized Email: " . $sanitizedEmail;
?>

Filter Functions: The filter function is used to filter the data coming from an insecure source.

Predefined Filter Constants: There are many predefined filter constants which are listed below:

Note: PHP filters are enabled by default in PHP 5.2.0 and newer versions. Installation requires for older versions. 

Reference: http://php.net/manual/en/filter.filters.sanitize.php


Article Tags :