PHP filter_input_array: How to Clean and Validate Input

PHP filter_input_array

The filter_input_array() filters multiple inputs in PHP at once. It helps you to clean and validate data.

Understand the filter_input_array Function

The filter_input_array() in PHP filters multiple inputs from GET, POST, COOKIE, SERVER, or ENV.

It applies validation and sanitization rules to each input based on a provided filter.

This function helps clean user data and reduce security risks like XSS and SQL injection. It also simplifies input handling that happens when processes multiple variables at once.

The syntax for filter_input_array() in PHP:

filter_input_array($type, $options, $add_empty)

Here are the parameters:

  • $type – The input type (INPUT_GET, INPUT_POST, INPUT_COOKIE, INPUT_SERVER, INPUT_ENV).
  • $options – An array of filters or a single filter for all inputs.
  • $add_empty – If true, missing keys return null. If false, missing keys are removed.

It returns:

  • An array of filtered values.
  • false if the input type is invalid.
  • null if no variables match.

Here is an example:

$options = [
    'name'  => FILTER_SANITIZE_STRING,
    'email' => FILTER_VALIDATE_EMAIL,
    'age'   => [
        'filter' => FILTER_VALIDATE_INT,
        'options' => ['min_range' => 18, 'max_range' => 100]
    ]
];

$input = filter_input_array(INPUT_POST, $options);

if ($input) {
    print_r($input);
} else {
    echo "Invalid input.";
}

Output:

Invalid input.

Here is how it works:

  • name is sanitized to remove unwanted characters.
  • email is validated as a proper email format.
  • age is validated as an integer within 18-100.
  • The function processes all inputs at once and reduces manual validation.

The Difference Between filter_input_array() and filter_var_array() in PHP

Here is a table that shows you the difference between them:

Featurefilter_input_array()filter_var_array()
Source of DataFetches and filters input directly from $_GET, $_POST, $_COOKIE, etc.Filters an existing array of data.
UsageUsed when retrieving and filtering user input.Used when filtering data already stored in a variable.
Input TypesRequires an input type (INPUT_GET, INPUT_POST, etc.).Works with any associative array.
SecurityHelps prevent using untrusted global variables.Requires manual handling of input sources.
Examplefilter_input_array(INPUT_POST, $filters);filter_var_array($data, $filters);

Example for filter_input_array function:

$options = [
    'name'  => FILTER_SANITIZE_STRING,
    'email' => FILTER_VALIDATE_EMAIL
];

$input = filter_input_array(INPUT_POST, $options);

Example for filter_var_array function:

$data = ['name' => '<h1>John</h1>', 'email' => 'invalid-email'];
$options = [
    'name'  => FILTER_SANITIZE_STRING,
    'email' => FILTER_VALIDATE_EMAIL
];

$filtered = filter_var_array($data, $options);

print_r($filtered);

Output:

Array
(
[name] => John
[email] =>
)

Use filter_input_array() if you need to fetch and filter input directly from user requests. Use filter_var_array() when you need to filter an existing array of data.

Custom filter_input_array in PHP

You can implement a custom filter_input_array() using the FILTER_CALLBACK filter. This lets you build your own function for the input data.

For example:


function sanitize_name($value) {
    return preg_replace("/[^a-zA-Z\s]/", "", $value); 
}


$options = [
    'name'  => ['filter' => FILTER_CALLBACK, 'options' => 'sanitize_name'],
    'email' => FILTER_VALIDATE_EMAIL,
    'age'   => [
        'filter' => FILTER_VALIDATE_INT,
        'options' => ['min_range' => 18, 'max_range' => 100]
    ]
];


$input = filter_input_array(INPUT_POST, $options);

if ($input) {
    print_r($input);
} else {
    echo "Invalid input.";
}

Output:

Invalid input.

Here is how it works:

  • The sanitize_name() function removes special characters from names.
  • FILTER_CALLBACK allows you to use a custom function for filtering.
  • FILTER_VALIDATE_EMAIL and FILTER_VALIDATE_INT handle validation for email and age.
  • filter_input_array() applies these rules to $_POST data.

How to Handle Input Fields within filter_input_array in PHP

filter_input_array() helps you to validate and sanitize multiple input fields at once. Follow these steps to handle input fields safely.

Here is how to define the rules of filtration:

$options = [
    'username' => FILTER_SANITIZE_STRING,  
    'email'    => FILTER_VALIDATE_EMAIL,  
    'age'      => [
        'filter'  => FILTER_VALIDATE_INT,
        'options' => ['min_range' => 18, 'max_range' => 100]
    ],
    'bio'      => FILTER_SANITIZE_FULL_SPECIAL_CHARS 
];

Use filter_input_array() to get and filter input:

$input = filter_input_array(INPUT_POST, $options);

Handle validation results:

if ($input) {
    if (!$input['email']) {
        echo "Invalid email.";
    } elseif (!$input['age']) {
        echo "Age must be between 18 and 100.";
    } else {
        print_r($input); // Process valid input
    }
} else {
    echo "No valid input received.";
}

Here is the output:

No valid input received.

Wrapping Up

In this article, you learned how filter_input_array() works and why you have to use them when you handle multiple inputs securely.

You also saw the difference between filter_input_array() and filter_var_array(). And also how to create custom filters

Here is a quick recap:

  • filter_input_array() filters multiple inputs at once from GET, POST, or other sources.
  • It applies sanitization and validation rules to prevent security risks.
  • filter_input_array() retrieves data directly, while filter_var_array() filters an existing array.
  • You can use FILTER_CALLBACK for custom filtering.
  • Proper input handling ensures safe and clean data processing.

Thank you for reading. Click here to see more PHP tutorials.

FAQ’s

What is filter_input_array() in PHP?

filter_input_array() filters multiple inputs from GET, POST, COOKIE, SERVER, or ENV at once. It applies validation and sanitization rules to prevent security risks like XSS and SQL injection.

What is the difference between filter_input_array() and filter_var_array()?

filter_input_array() retrieves and filters input directly from sources like $_POST or $_GET. filter_var_array() filters an existing array of data. Use filter_input_array() for user input and filter_var_array() when working with stored data.

How do I use filter_input_array() in PHP?

Define an array of filters and apply them to user input:
$options = [
    'name'  => FILTER_SANITIZE_STRING,
    'email' => FILTER_VALIDATE_EMAIL
];
$input = filter_input_array(INPUT_POST, $options);
This ensures only clean data enters your application.

Can I use a custom function with filter_input_array()?

Yes, use FILTER_CALLBACK to apply a custom function:
function sanitize_name($value) {
    return preg_replace("/[^a-zA-Z\s]/", "", $value);
}
$options = [
    'name' => ['filter' => FILTER_CALLBACK, 'options' => 'sanitize_name']
];
$input = filter_input_array(INPUT_POST, $options);
This allows advanced filtering beyond built-in options.

How do I validate multiple input fields with filter_input_array()?

Use an array of filters and handle the validation results:
$options = [
    'username' => FILTER_SANITIZE_STRING,
    'email'    => FILTER_VALIDATE_EMAIL
];
$input = filter_input_array(INPUT_POST, $options);
if (!$input['email']) {
    echo "Invalid email.";
} else {
    print_r($input);
}
This ensures all inputs meet security and formatting requirements.

Similar Reads

PHP Callable & Callback: Pass a Function to Another

The callback in PHP lets you pass functions as arguments and reuse code. It helps you to control how tasks…

PHP strtoupper Function: Convert Strings to Uppercase

Use strtoupper() function when you want to change all letters in a string to uppercase in PHP. It works with…

PHP array_key_first Function: How it Works with Examples

The array_key_first helps you to get the first key of an array directly in PHP. It saves time and removes…

PHP Assign Function to Variable – Examples and Explanation

PHP variable function is a variable that is used to assign a function name with parentheses (). However, the PHP interpreter…

PHP Filters: How to Validate and Sanitize User Inputs

User input can be unpredictable and dangerous. A simple form submission might carry malicious code or invalid data and lead…

PHP Bitwise Operators: AND, OR, XOR, NOT with Examples

Bitwise operators use symbols like &, |, and ^, and they work at the binary level. But once you understand…

PHP Type Juggling: How it Works Behind the Scenes

PHP type juggling refers to the dynamic system where the type of a variable is determined by its context in…

PHP $_SESSION: Secure Your Web Applications in PHP

It’s very important to remember user data for each session when building web applications. This enables a high level of…

PHP array_any: How it Works with Arrays with Examples

PHP 8.4 released the array_any to test if at least one element matches a condition. Understand the array_any Function in…

PHP MySQL Create Database: MySQLi & PDO Examples

If you are working with PHP and MySQL, one of the first tasks you may need is to create a…

Previous Article

PHP filter_input: How to Validate Input Securely

Next Article

PHP filter_id Function: How to Retrieve PHP Filter IDs

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *


Subscribe to Get Updates

Get the latest updates on Coding, Database, and Algorithms straight to your inbox.
No spam. Unsubscribe anytime.