PHP filter_input: How to Validate Input Securely

PHP filter_input

User input can be risky. Hackers exploit weak validation to inject malicious data. PHP filter_input() helps you sanitize and validate input securely. Learn how to use it to protect your application.

What is filter_input in PHP?

The filter_input() is a built-in PHP function that retrieves an external variable, such as user input from GET, POST, COOKIE, SERVER, or ENV, and applies a specified filter to sanitize or validate the data.

It prevents security threats like SQL injection, XSS (Cross-Site Scripting), and invalid input. This makes sure that the expected data is processed.

Here is the syntax:

filter_input(type, variable_name, filter, options)

Here are its parameters:

  • type (int, required) – Specifies the input source. Common values:
    • INPUT_GET – Data from $_GET
    • INPUT_POST – Data from $_POST
    • INPUT_COOKIE – Data from $_COOKIE
    • INPUT_SERVER – Data from $_SERVER
    • INPUT_ENV – Data from $_ENV
  • variable_name (string, required) – Name of the variable to filter.
  • filter (int, optional) – The filter to apply. Default is FILTER_DEFAULT, which applies no filtering. Common filters:
    • FILTER_SANITIZE_STRING – Removes special characters
    • FILTER_VALIDATE_EMAIL – Checks for a valid email format
    • FILTER_VALIDATE_INT – Ensures input is an integer
    • FILTER_SANITIZE_URL – Cleans a URL
  • options (mixed, optional) – An array of additional options for filtering, such as setting a value range for integers.

So, why is filter_input used for sanitizing and validating input in PHP?

User input can contain malicious code or unexpected values. If you trust input without validation that exposes your application to risks. filter_input() helps in two key ways:

  1. Sanitization – Removes unwanted characters and makes sure input meets security and formatting rules.
  2. Validation – Checks if input meets a defined format

Hence, you use filter_input() to improve security. It also reduces manual error handling and makes code cleaner.

Here is a quick example:

$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
if ($email === false) {
    echo "Invalid email format.";
} else {
    echo "Valid email: $email";
}

So, this code makes sure only properly formatted email addresses pass through. It returns false if input fails validation.

Types of Filters in filter_input

PHP provides two main types of filters for filter_input():

  1. Sanitization filters to remove or modify unwanted characters.
  2. Validation filters to check if input meets a specific format.

1. Sanitization Filters

To remove unwanted characters:

  • FILTER_SANITIZE_STRING (deprecated in PHP 8.1) removes HTML tags and special characters. Don’t use it in PHP 8+.
  • FILTER_SANITIZE_SPECIAL_CHARS converts special characters to HTML entities. It is needed to display safe output in HTML.
  • FILTER_SANITIZE_EMAIL removes invalid characters from an email address.
  • FILTER_SANITIZE_URL removes invalid characters from a URL.
  • FILTER_SANITIZE_NUMBER_INT keeps only digits, plus (+), and minus (-) signs.
  • FILTER_SANITIZE_NUMBER_FLOAT keeps digits and decimal points. Use with FILTER_FLAG_ALLOW_FRACTION.
  • FILTER_SANITIZE_ENCODED URL-encodes special characters. You can use it when you work with query strings.
  • FILTER_SANITIZE_FULL_SPECIAL_CHARS converts all special characters to HTML entities.

Here is an example:

$name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_SPECIAL_CHARS);
echo $name;

Removes special characters from name input.

2. Validation Filters

This helps you to check if the input matches the expected format:

  • FILTER_VALIDATE_BOOLEAN checks if the input is true, false, 1, 0, "yes", or "no".
  • FILTER_VALIDATE_EMAIL ensures the input is a valid email address.
  • FILTER_VALIDATE_URL ensures the input is a valid URL.
  • FILTER_VALIDATE_IP checks if the input is a valid IP address (IPv4 or IPv6).
  • FILTER_VALIDATE_IP with FILTER_FLAG_IPV4. ensures the input is a valid IPv4 address.
  • FILTER_VALIDATE_IP with FILTER_FLAG_IPV6. ensures the input is a valid IPv6 address.
  • FILTER_VALIDATE_INT validates that the input is an integer.
  • FILTER_VALIDATE_FLOAT Helps you to validate that the input is a floating-point number.
  • FILTER_VALIDATE_REGEXP validates the input against a custom regular expression.
  • FILTER_VALIDATE_DOMAIN (PHP 7.0+) checks if the input is a valid domain name.
  • FILTER_VALIDATE_MAC (PHP 7.0+) validates that the input is a valid MAC address.

Here is an example:

$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
if ($email === false) {
    echo "Invalid email.";
} else {
    echo "Valid email: $email";
}

This checks if the input is a valid email address.

Some filters allow extra options such as setting value ranges. Here is an example:

$age = filter_input(INPUT_POST, 'age', FILTER_VALIDATE_INT, [
    'options' => ['min_range' => 18, 'max_range' => 65]
]);
if ($age === false) {
    echo "Age must be between 18 and 65.";
} else {
    echo "Valid age: $age";
}

This makes sure age is an integer between 18 and 65.

Use filter_input to Validate Form Data

Using filter_input() to validate form data helps you make sure that the data entered by users meets expected formats and is safe for processing.

Below is an example of how to validate form data using filter_input(). Here is an example to validate form data with filter_input():

Consider a form where users enter their

  • Email.
  • Age.
  • Website.

Here’s how you can validate each field using filter_input():

HTML:

<form method="POST" action="process_form.php">
    <label for="email">Email:</label>
    <input type="text" id="email" name="email" required><br><br>
    
    <label for="age">Age:</label>
    <input type="text" id="age" name="age" required><br><br>
    
    <label for="website">Website:</label>
    <input type="text" id="website" name="website"><br><br>
    
    <button type="submit">Submit</button>
</form>

Here is the PHP code:


$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
if ($email === false) {
    echo "Invalid email format.<br>";
} else {
    echo "Valid email: $email<br>";
}


$age = filter_input(INPUT_POST, 'age', FILTER_VALIDATE_INT, [
    'options' => ['min_range' => 18, 'max_range' => 100]
]);
if ($age === false) {
    echo "Age must be a valid integer between 18 and 100.<br>";
} else {
    echo "Valid age: $age<br>";
}


$website = filter_input(INPUT_POST, 'website', FILTER_VALIDATE_URL);
if ($website === false) {
    echo "Invalid website URL.<br>";
} else {
    echo "Valid website: $website<br>";
}

Here is how it works:

  1. Email Validation:
    • The FILTER_VALIDATE_EMAIL filter ensures the email entered is in the correct format.
    • If the email is invalid, the function returns false.
  2. Age Validation:
    • The FILTER_VALIDATE_INT filter checks if the input is an integer.
    • The options parameter allows you to set a range for the integer.
    • If the age is not within the specified range, the function returns false.
  3. Website Validation:
    • The FILTER_VALIDATE_URL filter checks if the input is a valid URL.
    • If the website is invalid or empty, it returns false.

Sanitize User Input with filter_input

Use filter_input() in PHP to sanitize user input from GET, POST, and COOKIE data. This function helps prevent security risks like SQL injection and XSS attacks.

Here is an example:

$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
$age = filter_input(INPUT_POST, 'age', FILTER_SANITIZE_NUMBER_INT);
  • FILTER_SANITIZE_EMAIL: Removes invalid characters from an email.
  • FILTER_SANITIZE_NUMBER_INT: Removes non-numeric characters.

Here is another example of sanitizing and cleaning data, but validation makes sure that it meets specific rules.

$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
$age = filter_input(INPUT_POST, 'age', FILTER_VALIDATE_INT);
  • FILTER_VALIDATE_EMAIL checks if the email is valid.
  • FILTER_VALIDATE_INT makes sure the value is an integer.

So you have to sanitize first and then validate when needed. Use filter_input() instead of $_POST to improve security.

Wrapping Up

You learned how filter_input() helps sanitize and validate user input in PHP. You also explored different filters and their uses. Here is a quick recap:

  • Sanitization filters remove unwanted characters to make sure clean input. Examples include FILTER_SANITIZE_EMAIL, FILTER_SANITIZE_NUMBER_INT, and FILTER_SANITIZE_SPECIAL_CHARS.
  • Validation filters help you to check if the input matches a specific format. For examples include FILTER_VALIDATE_EMAIL, FILTER_VALIDATE_INT, and FILTER_VALIDATE_URL.

Thank you for reading. Click here to see more PHP tutorials.

FAQ’s

What is filter_input() in PHP?

filter_input() is a built-in PHP function that retrieves user input from sources like GET, POST, or COOKIE and applies a filter to sanitize or validate the data. It helps prevent security threats like SQL injection and XSS by ensuring only clean and expected data is processed.

How do I sanitize user input using filter_input()?

You can sanitize user input using different sanitization filters. For example:
$name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_SPECIAL_CHARS);
$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
$age = filter_input(INPUT_POST, 'age', FILTER_SANITIZE_NUMBER_INT);
These filters remove unwanted characters, ensuring safe and clean data.

How do I validate form data with filter_input()?

You can validate user input using validation filters. For example:
$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
$age = filter_input(INPUT_POST, 'age', FILTER_VALIDATE_INT, [
    'options' =&amp;amp;amp;amp;amp;gt; ['min_range' =&amp;amp;amp;amp;amp;gt; 18, 'max_range' =&amp;amp;amp;amp;amp;gt; 100]
]);
This ensures the email follows a valid format and the age is within a specified range.

What is the difference between sanitization and validation in filter_input()?

  • Sanitization removes or modifies unwanted characters (e.g., stripping HTML tags).
  • Validation checks if input meets a defined format (e.g., verifying an email format).
$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL); // Removes invalid characters  
$valid_email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL); // Checks if it's a valid email  
You should always sanitize first, then validate.

Why should I use filter_input() instead of $_POST in PHP?

Using $_POST directly can expose your application to security risks like SQL injection and XSS. filter_input() ensures that user input is filtered before being processed, making your code safer and reducing manual error handling.
Previous Article

PHP Arrow Functions: Understanding "fn" Syntax

Next Article

PHP filter_input_array: How to Clean and Validate Input

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Subscribe to Get Updates

Get the latest updates on Coding, Database, and Algorithms straight to your inbox.
No spam. Unsubscribe anytime.