PHP Filters Explained with Examples
PHP filters are used to validate and sanitize external input. They provide a secure way to check and clean data from users or external sources.
Types of PHP Filters
1. Validation Filters
Check if data meets certain criteria (returns boolean)
2. Sanitization Filters
Clean data by removing/encoding unwanted characters
Basic Syntax
// Validation
bool filter_var(mixed $value, int $filter, array $options)
// Sanitization
mixed filter_var(mixed $value, int $filter, array $options)
Example 1: Basic Validation
<?php
// Email validation
$email = "john.doe@example.com";
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Valid email address: $email\n";
} else {
echo "Invalid email address\n";
}
// Integer validation
$age = "25";
if (filter_var($age, FILTER_VALIDATE_INT)) {
echo "Valid integer: $age\n";
} else {
echo "Invalid integer\n";
}
// URL validation
$url = "https://www.example.com";
if (filter_var($url, FILTER_VALIDATE_URL)) {
echo "Valid URL: $url\n";
} else {
echo "Invalid URL\n";
}
// IP address validation
$ip = "192.168.1.1";
if (filter_var($ip, FILTER_VALIDATE_IP)) {
echo "Valid IP address: $ip\n";
} else {
echo "Invalid IP address\n";
}
?>
Example 2: Basic Sanitization
<?php
// Sanitize email
$dirty_email = "john.doe@example.com<script>";
$clean_email = filter_var($dirty_email, FILTER_SANITIZE_EMAIL);
echo "Sanitized email: $clean_email\n";
// Sanitize string
$dirty_string = "<script>alert('XSS')</script>Hello World!";
$clean_string = filter_var($dirty_string, FILTER_SANITIZE_STRING);
echo "Sanitized string: $clean_string\n";
// Sanitize URL
$dirty_url = "https://www.example.com?param=<script>malicious</script>";
$clean_url = filter_var($dirty_url, FILTER_SANITIZE_URL);
echo "Sanitized URL: $clean_url\n";
// Sanitize integer
$dirty_int = "123abc456";
$clean_int = filter_var($dirty_int, FILTER_SANITIZE_NUMBER_INT);
echo "Sanitized integer: $clean_int\n";
// Remove all characters except digits, + and -
$phone = "+1 (555) 123-4567";
$clean_phone = filter_var($phone, FILTER_SANITIZE_NUMBER_INT);
echo "Sanitized phone: $clean_phone\n";
?>
Example 3: Advanced Validation with Options
<?php
// Validate integer within range
$age = 25;
$options = array(
"options" => array(
"min_range" => 18,
"max_range" => 65
)
);
if (filter_var($age, FILTER_VALIDATE_INT, $options)) {
echo "Valid age: $age\n";
} else {
echo "Age must be between 18 and 65\n";
}
// Validate IP version
$ipv4 = "192.168.1.1";
$ipv6 = "2001:0db8:85a3:0000:0000:8a2e:0370:7334";
if (filter_var($ipv4, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
echo "Valid IPv4 address\n";
}
if (filter_var($ipv6, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
echo "Valid IPv6 address\n";
}
// Validate URL with required components
$url = "https://www.example.com/path?query=string#fragment";
if (filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_PATH_REQUIRED)) {
echo "URL has a path\n";
}
if (filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_QUERY_REQUIRED)) {
echo "URL has a query string\n";
}
?>
Example 4: Sanitization with Flags
<?php
// Sanitize string with different flags
$dirty_html = "<script>alert('XSS')</script><p>Hello <b>World</b>!</p>";
// Remove all HTML tags
$no_html = filter_var($dirty_html, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW);
echo "No HTML: $no_html\n";
// Encode special characters
$encoded = filter_var($dirty_html, FILTER_SANITIZE_SPECIAL_CHARS);
echo "Encoded: $encoded\n";
// Sanitize email with specific rules
$email = "john.doe@example.com\n";
$clean_email = filter_var($email, FILTER_SANITIZE_EMAIL, FILTER_FLAG_STRIP_LOW);
echo "Clean email: " . urlencode($clean_email) . "\n";
// Sanitize URL
$url = "https://example.com?param=<script>alert('test')</script>";
$clean_url = filter_var($url, FILTER_SANITIZE_URL, FILTER_FLAG_STRIP_LOW);
echo "Clean URL: $clean_url\n";
?>
Example 5: Filter Input Arrays
<?php
// Simulate form data
$_POST = [
'name' => 'John Doe<script>',
'email' => 'john@example.com',
'age' => '25',
'website' => 'https://example.com',
'bio' => '<p>This is my <b>bio</b>!</p>'
];
// Define filter rules
$filters = [
'name' => FILTER_SANITIZE_STRING,
'email' => FILTER_VALIDATE_EMAIL,
'age' => [
'filter' => FILTER_VALIDATE_INT,
'options' => ['min_range' => 18, 'max_range' => 100]
],
'website' => FILTER_VALIDATE_URL,
'bio' => FILTER_SANITIZE_SPECIAL_CHARS
];
// Apply filters
$filtered_data = filter_var_array($_POST, $filters);
echo "Filtered Data:\n";
print_r($filtered_data);
// Check for validation errors
foreach ($filtered_data as $field => $value) {
if ($value === false) {
echo "Validation failed for: $field\n";
}
}
?>
Example 6: Custom Validation with FILTER_CALLBACK
<?php
// Custom validation function
function validate_username($username) {
// Must be 3-20 characters, alphanumeric with underscores
return preg_match('/^[a-zA-Z0-9_]{3,20}$/', $username);
}
function validate_password($password) {
// At least 8 characters, one uppercase, one lowercase, one number
return preg_match('/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}$/', $password);
}
function sanitize_username($username) {
// Remove special characters, keep only alphanumeric and underscore
return preg_replace('/[^a-zA-Z0-9_]/', '', $username);
}
// Test data
$data = [
'username' => 'john_doe123!',
'password' => 'Weakpass'
];
// Apply custom filters
$filters = [
'username' => [
'filter' => FILTER_CALLBACK,
'options' => 'sanitize_username'
],
'password' => [
'filter' => FILTER_CALLBACK,
'options' => 'validate_password'
]
];
$result = filter_var_array($data, $filters);
echo "Username: " . $result['username'] . "\n";
echo "Password valid: " . ($result['password'] ? 'Yes' : 'No') . "\n";
// Another example with anonymous function
$numbers = [1, 2, 3, 4, 5];
$squared = array_map(function($n) {
return filter_var($n, FILTER_CALLBACK, [
'options' => function($value) {
return $value * $value;
}
]);
}, $numbers);
echo "Squared numbers: " . implode(', ', $squared) . "\n";
?>
Example 7: Comprehensive Form Validation
<?php
// Comprehensive form validation example
class FormValidator {
private $errors = [];
private $data = [];
public function validate($rules) {
$this->errors = [];
$this->data = [];
foreach ($rules as $field => $rule) {
$value = $_POST[$field] ?? null;
if (isset($rule['required']) && $rule['required'] && empty($value)) {
$this->errors[$field] = "$field is required";
continue;
}
if (!empty($value)) {
$filter = $rule['filter'] ?? null;
$options = $rule['options'] ?? [];
if ($filter) {
$filtered_value = filter_var($value, $filter, $options);
if ($filtered_value === false && isset($rule['validation'])) {
$this->errors[$field] = $rule['message'] ?? "Invalid $field";
} else {
$this->data[$field] = $filtered_value;
}
} else {
$this->data[$field] = $value;
}
}
}
return empty($this->errors);
}
public function getErrors() {
return $this->errors;
}
public function getData() {
return $this->data;
}
}
// Usage example
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$validator = new FormValidator();
$rules = [
'name' => [
'required' => true,
'filter' => FILTER_SANITIZE_STRING,
'message' => 'Please enter a valid name'
],
'email' => [
'required' => true,
'filter' => FILTER_VALIDATE_EMAIL,
'message' => 'Please enter a valid email address'
],
'age' => [
'required' => true,
'filter' => FILTER_VALIDATE_INT,
'options' => ['min_range' => 18, 'max_range' => 100],
'message' => 'Age must be between 18 and 100'
],
'website' => [
'required' => false,
'filter' => FILTER_VALIDATE_URL,
'message' => 'Please enter a valid URL'
]
];
if ($validator->validate($rules)) {
$data = $validator->getData();
echo "Form submitted successfully!\n";
print_r($data);
} else {
$errors = $validator->getErrors();
echo "Validation errors:\n";
print_r($errors);
}
}
?>
Example 8: Filter Input from Different Sources
<?php
// Filter input from different superglobals
echo "Filtering INPUT_GET:\n";
$get_filters = [
'page' => FILTER_VALIDATE_INT,
'search' => FILTER_SANITIZE_STRING
];
$filtered_get = filter_input_array(INPUT_GET, $get_filters);
print_r($filtered_get);
echo "\nFiltering INPUT_POST:\n";
$post_filters = [
'username' => FILTER_SANITIZE_STRING,
'email' => FILTER_VALIDATE_EMAIL
];
$filtered_post = filter_input_array(INPUT_POST, $post_filters);
print_r($filtered_post);
echo "\nFiltering INPUT_COOKIE:\n";
$cookie_filters = [
'session_id' => FILTER_SANITIZE_STRING,
'user_prefs' => ['filter' => FILTER_SANITIZE_STRING, 'flags' => FILTER_REQUIRE_ARRAY]
];
$filtered_cookie = filter_input_array(INPUT_COOKIE, $cookie_filters);
print_r($filtered_cookie);
// Individual input filtering
$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
$age = filter_input(INPUT_GET, 'age', FILTER_VALIDATE_INT, [
'options' => ['min_range' => 1, 'max_range' => 120]
]);
echo "\nIndividual values:\n";
echo "Email: " . ($email ?: 'Invalid') . "\n";
echo "Age: " . ($age ?: 'Invalid') . "\n";
?>
Common PHP Filter Constants
Validation Filters:
FILTER_VALIDATE_BOOLEAN
FILTER_VALIDATE_EMAIL
FILTER_VALIDATE_FLOAT
FILTER_VALIDATE_INT
FILTER_VALIDATE_IP
FILTER_VALIDATE_REGEXP
FILTER_VALIDATE_URL
Sanitization Filters:
FILTER_SANITIZE_EMAIL
FILTER_SANITIZE_ENCODED
FILTER_SANITIZE_NUMBER_FLOAT
FILTER_SANITIZE_NUMBER_INT
FILTER_SANITIZE_SPECIAL_CHARS
FILTER_SANITIZE_STRING
FILTER_SANITIZE_URL
Best Practices
- Always validate and sanitize user input
- Use appropriate filters for different data types
- Combine validation and sanitization when necessary
- Use custom callbacks for complex validation rules
- Validate data before sanitizing when possible
- Use
filter_input_array()
for processing multiple inputs - Always provide meaningful error messages
PHP filters provide a robust and secure way to handle external input, helping to prevent common security vulnerabilities like SQL injection and XSS attacks.
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Terms Disclaimer About Us Contact Us
Copyright 2023-2025 © All rights reserved.