In web development, forms are an important means of interacting with users. Properly validating user input is crucial for data security and integrity. PHP provides the filter_input function, making it easier and more efficient to validate and filter user input. This article explains how to use filter_input to check user input and provides practical code examples.
The filter_input function is used to filter and validate user input. It accepts three main parameters: input type (source), input name, and filter type. Here is a basic example:
$input = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
if ($input) {
echo 'Valid email address.';
} else {
echo 'Please enter a valid email address.';
}In the example, filter_input is used to validate the email field submitted via POST. FILTER_VALIDATE_EMAIL checks whether the email format is valid. If valid, it outputs “Valid email address,” otherwise prompts the user to enter a correct email.
filter_input supports multiple filter types to validate different kinds of input. Here are some commonly used filters:
$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
if (!$email) {
echo 'Please enter a valid email address.';
}$age = filter_input(INPUT_POST, 'age', FILTER_VALIDATE_INT);
if (!$age) {
echo 'Please enter a valid age.';
}$url = filter_input(INPUT_POST, 'url', FILTER_VALIDATE_URL);
if (!$url) {
echo 'Please enter a valid URL.';
}$name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING);
if (!$name) {
echo 'Please enter a valid name.';
}Besides built-in filters, you can create custom functions to validate user input. A custom function accepts one parameter and returns a validation result (true or false). Example:
function validate_username($username) {
// Username must start with a letter and contain only letters, numbers, and underscores
return preg_match('/^[a-zA-Z][a-zA-Z0-9_]*$/', $username);
}
$username = filter_input(INPUT_POST, 'username', FILTER_CALLBACK, array('options' => 'validate_username'));
if (!$username) {
echo 'Please enter a valid username.';
}In this example, the validate_username function uses a regular expression to check that the username starts with a letter and contains only letters, numbers, and underscores. Then, FILTER_CALLBACK is used to call the custom function to validate the input.
This article introduced how to use PHP's filter_input function for user input validation, including basic usage, common filter types, and custom filter function examples. Proper input validation is essential for ensuring data integrity and application security. These techniques can help improve the quality and user experience of your web applications.