PHP Filters

PHP Filters

Validating data is critical for web security. The PHP filter extension provides highly robust and native functions to both validate and sanitize external input (such as user form data).


The filter_var() Function

The filter_var() function is the engine of the PHP filter extension. It both validates and sanitizes data depending on the filter flag you provide.

It takes two parameters:

  1. The variable you want to check.
  2. The type of check (the filter flag) to use.

1. Sanitizing a String

The FILTER_SANITIZE_STRING filter removes all HTML tags from a string. If a user tries to input a script like <script>alert(1);</script>, this filter safely strips the tags.

Sanitize Example

<?php
$str = "<h1>Hello World!</h1>";

// Remove HTML tags from string $newstr = filter_var($str, FILTER_SANITIZE_STRING);

echo $newstr; // Outputs: Hello World! ?>

(Note: FILTER_SANITIZE_STRING has been deprecated in recent PHP 8+ versions in favor of htmlspecialchars(), but understanding the concept of sanitization filters is vital).


2. Validating an Integer

The FILTER_VALIDATE_INT filter checks if a variable is a valid integer.

Validate Example

<?php
$int = 100;

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

Exercise

?

Which function is primarily used to apply validation and sanitization filters to a variable?