How to Use filter_input in PHP: Syntax and Examples
Use
filter_input in PHP to get external input like GET or POST variables safely by specifying the input type and variable name. It optionally allows filtering or validating the input using built-in filters to avoid unsafe data.Syntax
The filter_input function has this syntax:
type: The input source, likeINPUT_GET,INPUT_POST, etc.variable_name: The name of the input variable to get.filter: (Optional) The filter to apply, likeFILTER_SANITIZE_STRINGorFILTER_VALIDATE_INT.options: (Optional) Additional options or flags for the filter.
php
mixed filter_input(int $type, string $variable_name, int $filter = FILTER_DEFAULT, array|int $options = 0)
Example
This example shows how to get a 'name' from a GET request and sanitize it to remove harmful characters.
php
<?php // Simulate a GET request for demonstration $_GET['name'] = "<script>alert('x')</script>John"; // Get and sanitize the 'name' parameter from GET $name = filter_input(INPUT_GET, 'name', FILTER_SANITIZE_FULL_SPECIAL_CHARS); echo "Sanitized name: " . $name; ?>
Output
Sanitized name: alert('x')John
Common Pitfalls
Common mistakes include:
- Not specifying the correct input type like
INPUT_POSTorINPUT_GET. - Forgetting to use filters, which can lead to unsafe data.
- Expecting
filter_inputto work on variables not from external sources (it only works on superglobals).
Example of a wrong and right way:
php
<?php // Wrong: Trying to filter a normal variable $name = "<b>John</b>"; // This will return null because $name is not from input $filtered = filter_input(INPUT_GET, 'name', FILTER_SANITIZE_STRING); echo $filtered === null ? "No input found" : $filtered; // Right: Use filter_var for normal variables $filtered_correct = filter_var($name, FILTER_SANITIZE_STRING); echo "\nFiltered normal variable: " . $filtered_correct; ?>
Output
No input found
Filtered normal variable: John
Quick Reference
| Parameter | Description | Example |
|---|---|---|
| type | Input source constant | INPUT_GET, INPUT_POST, INPUT_COOKIE |
| variable_name | Name of the input variable | 'username', 'age' |
| filter | Filter to apply | FILTER_SANITIZE_STRING, FILTER_VALIDATE_INT |
| options | Extra filter options | ['options' => ['min_range' => 1]] |
Key Takeaways
Use filter_input to safely get and filter external input like GET or POST variables.
Always specify the correct input type and use appropriate filters to avoid unsafe data.
filter_input only works with external input sources, not normal PHP variables.
For filtering normal variables, use filter_var instead.
Common filters include FILTER_SANITIZE_STRING and FILTER_VALIDATE_INT.