WikiGalaxy

Personalize

PHP Filters

Introduction to PHP Filters:

PHP filters are used to validate and sanitize external input. They help in ensuring that the data is safe and meets the expected format, thus preventing potential security vulnerabilities like XSS and SQL injection.

Why Use PHP Filters?

Using PHP filters allows developers to handle data validation and sanitization systematically, reducing the risk of errors and enhancing code maintainability.

Filter Functions

filter_var()

The filter_var() function is used to both validate and sanitize data. It takes a variable and applies a specified filter.


<?php
$email = "someone@example.com";
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo("Email is valid");
} else {
    echo("Email is not valid");
}
?>
      

Sanitizing Input

filter_var() for Sanitization

Sanitization removes unwanted characters from data. This is crucial when dealing with user inputs.


<?php
$url = "http://example.com";
$sanitized_url = filter_var($url, FILTER_SANITIZE_URL);
echo $sanitized_url;
?>
      

Validating Integers

FILTER_VALIDATE_INT

This filter checks whether the specified variable is a valid integer.


<?php
$int = 100;
if (filter_var($int, FILTER_VALIDATE_INT) !== false) {
    echo("Integer is valid");
} else {
    echo("Integer is not valid");
}
?>
      

Sanitizing Strings

FILTER_SANITIZE_STRING

This filter removes tags and optionally removes or encodes special characters from a string.


<?php
$str = "<h1>Hello</h1>";
$sanitized_str = filter_var($str, FILTER_SANITIZE_STRING);
echo $sanitized_str;
?>
      

Validating URLs

FILTER_VALIDATE_URL

This filter checks whether the specified variable is a valid URL.


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

Sanitizing Email Addresses

FILTER_SANITIZE_EMAIL

This filter removes all illegal characters from an email address.


<?php
$email = "someone@exa(mple.com";
$sanitized_email = filter_var($email, FILTER_SANITIZE_EMAIL);
echo $sanitized_email;
?>
      

Validating IP Addresses

FILTER_VALIDATE_IP

This filter checks whether the specified variable is a valid IP address.


<?php
$ip = "127.0.0.1";
if (filter_var($ip, FILTER_VALIDATE_IP)) {
    echo("IP is valid");
} else {
    echo("IP is not valid");
}
?>
      

Custom Filters

Creating Custom Filters

PHP allows for the creation of custom filters using callback functions, providing flexibility for specific validation needs.


<?php
function custom_filter($value) {
    return ($value === "custom") ? true : false;
}
$value = "custom";
if (filter_var($value, FILTER_CALLBACK, array("options"=>"custom_filter"))) {
    echo("Value is valid");
} else {
    echo("Value is not valid");
}
?>
      
logo of wikigalaxy

Newsletter

Subscribe to our newsletter for weekly updates and promotions.

Privacy Policy

 • 

Terms of Service

Copyright © WikiGalaxy 2025