← Back to Chapters

PHP Filter Validations

? PHP Filter Validations

? Quick Overview

PHP filter validation functions are used to validate and sanitize user input before processing. This helps prevent security risks like SQL Injection and XSS attacks.

? Key Concepts

  • Validation checks if data matches expected format
  • Sanitization cleans unwanted characters
  • PHP provides built-in filter constants

? Syntax & Theory

The filter_var() function validates or sanitizes a single variable using predefined filters.

? Code Example

? View Code Example
// Demonstrating PHP filter validation and sanitization
<?php
$email = "john.doe@example.com";
$url = "https://www.example.com";
$age = "25";

if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "$email is a valid email address.
";
}

if (filter_var($url, FILTER_VALIDATE_URL)) {
echo "$url is a valid URL.
";
}

$dirty_string = "<h1>Welcome!</h1>";
$sanitized_string = htmlspecialchars($dirty_string);
echo "Sanitized string: $sanitized_string
";

if (filter_var($age, FILTER_VALIDATE_INT)) {
echo "$age is a valid integer.
";
}
?>

? Live Output / Explanation

The script validates email, URL, and integer values while sanitizing HTML tags from strings.

? Interactive Example

Try replacing values with invalid email or URL strings and observe validation results.

? Use Cases

  • Form input validation
  • API request handling
  • Secure database operations

✅ Tips & Best Practices

  • Always validate before sanitizing
  • Use specific filters for data types
  • Never trust user input

? Try It Yourself

  • Create a form and validate inputs
  • Test invalid email formats
  • Sanitize user comments before display