Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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, orINPUT_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.
