← Back to Chapters

PHP filter_input() Function

?️ PHP filter_input() Function

? Quick Overview

The filter_input() function is used to fetch external input data and apply validation or sanitization in a single step. It is commonly used with form data, URLs, cookies, and server variables to improve application security.

? Key Concepts

  • Fetches input from external sources
  • Supports validation and sanitization
  • Returns NULL for invalid input
  • Helps prevent security vulnerabilities

? Syntax & Theory

Function Syntax:

? View Code Example
// filter_input syntax structure
filter_input(int $type, string $variable_name, int $filter = FILTER_DEFAULT, mixed $options = null);

? Code Example

? View Code Example
// Simulating GET request data
$_GET['email'] = "test@example.com";
$_GET['age'] = "25";

// Validate email input
$email = filter_input(INPUT_GET, 'email', FILTER_VALIDATE_EMAIL);
if ($email) {
echo "Valid Email: $email
";
} else {
echo "Invalid Email
";
}

// Validate integer input
$age = filter_input(INPUT_GET, 'age', FILTER_VALIDATE_INT);
if ($age) {
echo "Valid Age: $age
";
} else {
echo "Invalid Age
";
}

? Live Output / Explanation

  • Email is checked using FILTER_VALIDATE_EMAIL
  • Age is validated using FILTER_VALIDATE_INT
  • Invalid inputs return NULL

? Interactive Insight

You can replace INPUT_GET with INPUT_POST and test the behavior using an HTML form submission.

? Use Cases

  • Form input validation
  • Secure login systems
  • Filtering URL parameters
  • Sanitizing user-submitted data

✅ Tips & Best Practices

  • Always validate before processing input
  • Use specific filters instead of default
  • Combine with output escaping when needed

? Try It Yourself

  • Validate phone numbers and URLs
  • Switch from GET to POST inputs
  • Test invalid values deliberately
  • Add custom filter options