Filter Functions
Data can be grabbed with the $_GET
or $_POST
superglobal variables. PHP offers an alternative solution, which is to use filter functions.
PHP's filter functions are used to validate and sanitize data. These include various functions like filter_var()
, filter_input()
, filter_input_array()
, and more.
The filter_input()
function specifically fetches a value from a specific input data (such as $_GET
, $_POST
, etc.) and filters it according to the specified filter.
Why use a filter function?
Accessing $_GET
or $_POST
directly means grabbing the user's input exactly as they entered it, with no checks or cleaning. It's like accepting a package without checking what's inside. If someone wants to cause trouble, they might be able to.
Using filter_input()
is like having a security check on that package. It ensures that what's inside is exactly what you were expecting, nothing more, nothing less. It adds a layer of safety and trust to the information you're collecting from users.
Parameters
Its syntax is:
filter_input(
int $type,
string $var_name,
int $filter = FILTER_DEFAULT,
array|int $options = 0
): mixed
Here's what the parameters mean:
-
$type
: This is a required parameter that defines the type of input to get. It can be one of the following constants:INPUT_GET
: For GET data ($_GET
).INPUT_POST
: For POST data ($_POST
).INPUT_COOKIE
: For COOKIE data.INPUT_SERVER
: For SERVER variables.INPUT_ENV
: For environment variables.
-
$var_name
: This required parameter specifies the name of the variable to filter. -
$filter
: This optional parameter defines the ID of the filter to apply. If omitted, the function will use the default filter, which does not alter the variable. -
$options
: This is an optional parameter that defines flags and options according to the filter. It can be either a single flag or an associative array of options.
Basic Example
Let's say you have a webpage with a form asking for a user's age, and they enter it in a text box.
$age = filter_input(INPUT_POST, 'age');
The above code is the equivalent of accessing the input with the $_POST
variable like so:
$age = $_POST['age'];
The main advantage of using the filter_input()
function is the ability to apply validation filters.
Validation Filters
PHP offers several filters, which can be specified with predefined constants. These filters allow you to validate different types of input data according to specific rules, making it easier to ensure that the data you receive meets the expectations and requirements of your application.
Filter Name | Description |
---|---|
FILTER_VALIDATE_BOOLEAN | Validates value as a boolean. |
FILTER_VALIDATE_DOMAIN | Validates value as a domain name. |
FILTER_VALIDATE_EMAIL | Validates value as an email address. |
FILTER_VALIDATE_FLOAT | Validates value as a float number. |
FILTER_VALIDATE_INT | Validates value as an integer. |
FILTER_VALIDATE_IP | Validates value as an IP address. |
FILTER_VALIDATE_MAC | Validates value as a MAC address. |
FILTER_VALIDATE_REGEXP | Validates value against a regular expression. |
FILTER_VALIDATE_URL | Validates value as a URL. |
Imagine you have a form on your website where users can enter their age, and you want to make sure that the entered value is an actual number.
The input would probably look something like this:
<input type="text" name="age" />
Here's the code you would use to validate the field:
$age = filter_input(INPUT_POST, 'age', FILTER_VALIDATE_INT);
if ($age === false) {
echo "Please enter a valid number for your age.";
} else {
echo "Thank you for entering your age!";
}
The first line uses the filter_input()
function to check the value of 'age' that the user entered in the form (using the POST method).
INPUT_POST
: This tells PHP to look at the data sent by a form using the POST method.'age'
: This is the name of the input field in the form where the user enters their age.FILTER_VALIDATE_INT
: This tells PHP that the value must be a valid integer (whole number).
If the value entered is not a valid integer, filter_input()
will return false. In this case, we print an error message asking for a valid number. If the value is a valid integer, we print a thank-you message.
So with just one line of code using the filter_input()
function, you can make sure that the age entered by the user is a whole number and provide feedback if it's not. It's a simple and powerful way to validate user input.
Validating Multiple inputs
Typically, your form won't have just one input. Validating multiple inputs is possible with a function called filter_input_array()
.
The filter_input_array()
function in PHP is used to validate and sanitize multiple inputs at once. It's extremely useful when you have several pieces of data to validate, such as a form with multiple fields. Rather than calling filter_input()
for each individual input, you can use filter_input_array()
to handle them all at once, making your code cleaner and more efficient.
Parameters
Here's the function definition
filter_input_array(int $type, array|int $options = FILTER_DEFAULT, bool $add_empty = true): array|false|null
$type
: (Required) This parameter specifies the input type that you want to filter. It can be the same inputs used in thefilter_input()
function.$options
: (Optional) An array defining the arguments. It can be an array of filter IDs (likeFILTER_VALIDATE_INT
) or an array of associative arrays specifying individual filter rules, including filters, flags, options, etc. If this parameter is an array, the return value will also be an array.$add_empty
: (Optional) This boolean parameter controls whether to add empty elements for missing optional inputs. The default value istrue
.
The function returns an associative array of values obtained and filtered as per the specified rules, or false
if the filter fails or if the provided inputs are not set.
Usage
You define an array of inputs you want to filter, specifying the input type (like INPUT_POST
or INPUT_GET
) and the filtering rules for each input. Then you call filter_input_array()
, passing it the array, and it returns an associative array with the filtered data.
Let's say you have a form where users can enter their name, email, and age, and you want to validate all these inputs.
Here's how you could use filter_input_array()
to do that:
$filters = [
'name' => ['filter' => FILTER_SANITIZE_STRING],
'email' => ['filter' => FILTER_VALIDATE_EMAIL],
'age' => ['filter' => FILTER_VALIDATE_INT]
];
$result = filter_input_array(INPUT_POST, $filters);
if ($result['name'] && $result['email'] && $result['age']) {
echo "All inputs are valid!";
} else {
echo "Please enter valid data.";
}
We create an array $filters
where we define the filter
rules for each input. The key name must correspond to the field we'd like to validate. The value is an array of options. In our case, we're adding an option called filter
to apply a specific filter. In this case, we're sanitizing the name to be a string, validating the email, and making sure the age is an integer.
We call filter_input_array
with INPUT_POST
(since we're expecting POST data) and the $filters
array. This will return an associative array $result
where the keys are the input names, and the values are the filtered inputs.
We then check if all the filtered results are valid (not false
). If they are, we print a success message; otherwise, we print an error message.
Filtering Variables
The filter_input()
function is designed to filter data directly from global input variables like $_GET
, $_POST
, etc. However, in many scenarios, you may have data stored in other variables that you need to validate or sanitize. This is where the filter_var()
function comes into play.
The filter_var()
function filters a variable with a specified filter. It can be used to validate or sanitize data that are not coming directly from the global input arrays, such as variables from a database, configuration files, or data manipulated within your code.
Here's the function definition:
filter_var(mixed $value, int $filter = FILTER_DEFAULT, array|int $options = 0): mixed
$value
: (Required) The value you want to filter.$filter
: (Optional) The ID of the filter to apply, likeFILTER_VALIDATE_EMAIL
. The default isFILTER_DEFAULT
, which doesn't alter the variable.$options
: (Optional) Associative array of options or bitwise disjunction of flags pertaining to the filter.
Suppose you have a variable containing an email address that you retrieved from a database, and you want to verify that it's a valid email format:
$email = "example@example.com";
$filtered_email = filter_var($email, FILTER_VALIDATE_EMAIL);
if ($filtered_email) {
echo "This is a valid email address!";
} else {
echo "This is not a valid email address.";
}
Here, the filter_var()
function checks whether the $email
variable contains a valid email address format.
The filter_var()
function is versatile and can be applied to any data within your application, not just user inputs. This makes it a valuable tool for validating and sanitizing data from various sources, ensuring that your application handles clean and secure data according to the defined rules and expectations.
Filtering Multiple Variables
Just like the filter_var()
function allows you to filter a single variable, the filter_var_array()
function enables you to filter multiple variables at once. This function can be especially helpful when you have an array of data that you want to validate or sanitize, and it can be applied to any array of data, not just the global input arrays like $_GET
or $_POST
.
Here's the function definition:
filter_var_array(array $array, array|int $options = FILTER_DEFAULT, bool $add_empty = true): array|false|null
$array
: (Required) An array containing the values to filter.$options
: (Optional) An array defining the filters to apply to the data. It can be an array of filter IDs or an array of associative arrays specifying individual filter rules, including filters, flags, options, etc.$add_empty
: (Optional) A boolean that controls whether to add empty elements for missing optional inputs. The default value is true.
Imagine you have an array of user information that you want to validate, including name, age, and email:
$userData = [
'name' => 'John',
'age' => '25',
'email' => 'john@example.com',
];
$filters = [
'name' => ['filter' => FILTER_SANITIZE_STRING],
'age' => ['filter' => FILTER_VALIDATE_INT],
'email' => ['filter' => FILTER_VALIDATE_EMAIL]
];
$result = filter_var_array($userData, $filters);
if ($result !== false) {
echo "All inputs are valid!";
} else {
echo "Please enter valid data.";
}
We create an array $filters
where we define the filter rules for each input. We're sanitizing the name to be a string, validating the age as an integer, and making sure the email is in a valid format.
We call filter_var_array()
with the $userData
array and the $filters
array. This returns an associative array $result
with the filtered inputs. We then check if the filtered results are valid (not false
), and if so, print a success message.
Key Takeaways
- PHP filter functions are essential for data validation and sanitization, helping ensure that incoming data meets specific criteria and is free from harmful or undesired content.
- The
filter_var()
function is used for filtering a single variable with a specified filter. Useful for data that are not coming directly from global input arrays, like variables from databases or manipulated within your code. - The
filter_var_array()
function allows the filtering of multiple variables at once by applying specified filters to an array of data. It streamlines the process and ensures consistency in validation and sanitization. - The
filter_input()
function targets data from specific global input variables like$_GET
,$_POST
, etc., applying a single filter to a single input. - Various filter options are available for different data types (e.g.,
FILTER_VALIDATE_INT
,FILTER_SANITIZE_EMAIL
). - If validation or sanitization fails, functions return
false
. It allows for immediate error detection and feedback.