When building web applications, validating user input is a crucial step. It protects against invalid data, potential security threats, and system errors. PHP offers a powerful built-in function — filter_input_array() — that enables you to validate multiple fields in one go.
The filter_input_array() function allows developers to apply different validation and sanitization rules to multiple input fields simultaneously. It takes two parameters:
Input type (such as INPUT_GET, INPUT_POST, etc.)
An associative array of filter rules
Here are the typical constants used to specify the type of input source:
const INPUT_GET = 'get';
const INPUT_POST = 'post';
const INPUT_COOKIE = 'cookie';
const INPUT_SERVER = 'server';
Filter rules are defined as an associative array where the keys are the input field names and the values are the corresponding filters. These can be either predefined PHP filter constants or arrays that include additional options. For example:
$filters = array(
'username' => FILTER_SANITIZE_STRING,
'email' => FILTER_VALIDATE_EMAIL,
'password' => array(
'filter' => FILTER_VALIDATE_REGEXP,
'options' => array('regexp' => '/^[a-zA-Z0-9]{6,}$/')
)
);
Explanation:
username uses FILTER_SANITIZE_STRING to remove unwanted characters and HTML tags.
email is validated using FILTER_VALIDATE_EMAIL to ensure it's in a proper email format.
password is validated with a regular expression to ensure it contains only letters and numbers and is at least 6 characters long.
Below is a complete example demonstrating how to apply filter rules using filter_input_array() with data from a POST request:
const INPUT_GET = 'get';
const INPUT_POST = 'post';
$filters = array(
'username' => FILTER_SANITIZE_STRING,
'email' => FILTER_VALIDATE_EMAIL,
'password' => array(
'filter' => FILTER_VALIDATE_REGEXP,
'options' => array('regexp' => '/^[a-zA-Z0-9]{6,}$/')
)
);
$input = filter_input_array(INPUT_POST, $filters);
if ($input) {
// Input validation successful
// Proceed with further processing
echo 'User input validated successfully!';
} else {
// Input validation failed
echo 'User input validation failed!';
}
This code defines the filter rules, then applies them using filter_input_array() to the incoming POST data. If validation passes, you can safely proceed with handling the input. Otherwise, an error message is displayed.
Using filter_input_array() in PHP is a clean and efficient way to validate multiple user inputs. It helps keep your code organized while ensuring that only valid and safe data is processed. Defining custom rules per field allows for flexible, secure form validation — an essential part of any modern PHP application.