Filter in PHP
? Filters in PHP
PHP has a built-in filter extension that provides a simple and powerful way to validate and sanitize external input (like from forms, URLs, and cookies). This helps prevent security vulnerabilities such as XSS and SQL injection.
? Why Use Filters?
? Clean data before saving to DB
? Validate email, IP, integers, URLs
? Remove unwanted characters
? Prevent malicious input
? 1. Sanitizing Data
Used to clean input by removing undesired characters.
$name = "<h1>John</h1>";$clean = filter_var($name, FILTER_SANITIZE_STRING); // Old PHP versions$clean = strip_tags($name); // Newer preferred methodecho $clean; // Output: JohnCommon Sanitizers:
| Filter | Purpose |
|---|---|
FILTER_SANITIZE_STRING | Removes tags (deprecated) |
FILTER_SANITIZE_EMAIL | Removes illegal characters from email |
FILTER_SANITIZE_URL | Removes illegal characters from URL |
FILTER_SANITIZE_NUMBER_INT | Keeps digits and +/- |
? 2. Validating Data
Checks if data is in a valid format (returns true or false).
$email = "test@example.com";if (filter_var($email, FILTER_VALIDATE_EMAIL)) { echo "Valid email";} else { echo "Invalid email";}Common Validators:
| Filter | Description |
|---|---|
FILTER_VALIDATE_INT | Validates integer |
FILTER_VALIDATE_FLOAT | Validates float |
FILTER_VALIDATE_EMAIL | Validates email |
FILTER_VALIDATE_URL | Validates URL |
FILTER_VALIDATE_IP | Validates IP address |
FILTER_VALIDATE_BOOLEAN | Validates true/false |
? 3. With Options
$age = "25";if (filter_var($age, FILTER_VALIDATE_INT, ["options" => ["min_range" => 18, "max_range" => 30]])) { echo "Age is valid.";} else { echo "Age is not in range.";}? 4. filter_input() Example
// Validating input from a GET form$number = filter_input(INPUT_GET, "num", FILTER_VALIDATE_INT);if ($number !== false) { echo "Valid number: $number";} else { echo "Invalid input.";}? Best Practices
Use filters to clean all user inputs.
Validate before saving or processing.
Combine sanitization + validation where necessary.