filter_input() function in PHP

The filter_input() function gets an external variable by name and optionally filters it using built-in PHP filters. It's commonly used to sanitize and validate user input from forms, URLs, cookies, and server variables.

Syntax

filter_input(type, var, filtername, options)

Parameters

  • type − Specifies the input type. Five constants are available: INPUT_GET, INPUT_POST, INPUT_COOKIE, INPUT_SERVER, or INPUT_ENV.

  • var − The name of the variable to filter.

  • filtername − The ID of the filter to apply (e.g., FILTER_VALIDATE_EMAIL, FILTER_SANITIZE_STRING).

  • options − Optional flags or options for the filter.

Return Value

Returns the filtered variable value on success, false on failure, or null if the variable is not set.

Example

Here's a demonstration using a simulated POST variable ?

<?php
// Simulate POST data
$_POST['email'] = 'invalid-email';
$_POST['age'] = '25';

// Validate email
$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
if ($email === false || $email === null) {
    echo "E-Mail isn't valid!<br>";
} else {
    echo "E-Mail is valid: " . $email . "<br>";
}

// Validate integer
$age = filter_input(INPUT_POST, 'age', FILTER_VALIDATE_INT);
if ($age !== false && $age !== null) {
    echo "Age is valid: " . $age;
} else {
    echo "Age isn't valid!";
}
?>
E-Mail isn't valid!
Age is valid: 25

Conclusion

The filter_input() function provides a secure way to validate and sanitize external input data. Always check return values for false or null to handle validation failures properly.

Updated on: 2026-03-15T07:32:31+05:30

710 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements