PHP Input Filtering

Last modified on May 9th, 2018 by Vincy.

PHP is one of the easy handling languages which makes developers be comfortable to work with. It provides functions to sanitize and validate the outside user input. These functions are in the PHP filters extension. This extension is enabled by default as of the PHP version 5.2.0. It can be explicitly configured with the PHP configuration file. The outsiders’ can send their inputs in many ways. For example, they can post the input via a HTML form, send API params via REST clients and more. These inputs have to be sanitized and validated before processing them. We have seen the example of doing client-side validation.

PHP filters extension provides functions and filter constants to validate the different type of input. The filter_list() function will return the array of filters supported by this extension. These filters will remove the unexpected data from the user input and validate the format after sanitization. In this post, we are going to see the list of filter functions and its use. Also, I have added an example code for validating the username and email using the PHP filter functions. The name and email data will be posted via a HTML form.

PHP Filter Functions

These are the list of PHP filter functions available in the PHP filter extension.

filter_has_var()

This function is used to check if the specified type of the variable name exists or not.

filter_has_var(int $type , string $variable_name);

The possible values of $type are INPUT_GET, INPUT_POST, INPUT_COOKIE, INPUT_SERVER, or INPUT_ENV. The $variable_name is index variable to be used to check the input.

filter_id()

This function will return the id of the specified filter_nam.

filter_id(string $filter_name);

filter_input_array()

It accepts an array of mixed filter definitions to validate the input type.

filter_input_array ( int $type, mixed $definition, bool $add_empty = TRUE )

The filter definition and add_empty arguments are optional. The $add_empty will be TRUE by default to return NULL for the unset variable index.

filter_input()

The PHP filter_input function validates input type with single filter id instead of the mixed definition we have used for filter_input_array.

filter_input ( int $type, string $variable_name, int $filter = FILTER_DEFAULT, mixed $options );

filter_list()

As we have mentioned above in the PHP filter introduction, this function returns all the list of filters supported by this extension.

filter_list();

filter_var_array()

This function accepts an array of input data and filters definition with the add_empty flag to validate the input array.

filter_var_array ( array $data , mixed $definition , bool $add_empty = TRUE  )

filter_var()

It takes a single input and filter id for validation.

filter_var ( $variable , int $filter = FILTER_DEFAULT , mixed $options )

PHP Example: Validating HTML Form Posts using Filters Functions

In this example, I have created a HTML form to let the user enter their name and email address. On submitting this form the input data are posted to the PHP file. In PHP code, the $_POST data are sanitized and validated using PHP filter function filter_var.

HTML Code to Display the Form and Client-Side Validation Script

Below code shows the HTML for displaying the form with the user name and email address field. On submitting this form the fnSubscribe() JavaScript function is called and to do the not-empty check for the form fields in the client-side.

<form name="frmSubscription" action="" method="POST"
    onSubmit="return fnSubscribe();">
    <input type="text" name="userName" /><br /> <input type="text"
        name="userEmail" /><br /> <input type="submit"
        name="subscribe" value="Subscribe" />
</form>

<script>
	function fnSubscribe() {
		if (document.frmSubscription.userName.value == "") {
			return false;
		}
		if (document.frmSubscription.userEmail.value == "") {
			return false;
		}
		return true;
	}
</script>

PHP Filter Sanitization and Validation Code

The following PHP code applies sanitization and validation filter on the form post data. After filtering the user input posted via the HTML form, I have created the INSERT query to add the user data to the database. I used FILTER_SANITIZE_STRING and FILTER_SANITIZE_EMAIL filter to sanitise the username and email data respectively. And then, I used FILTER_VALIDATE_EMAIL to check if the email data is in valid format.

<?php
if (! empty($_POST["subscribe"])) {
    $userName = filter_input(INPUT_POST, "userName", FILTER_SANITIZE_STRING);
    $userEmail = filter_input(INPUT_POST, "userEmail", FILTER_SANITIZE_EMAIL);
    
    $userEmail = filter_var($userEmail, FILTER_VALIDATE_EMAIL);
    
    if (! empty($userName) && ! empty($userEmail)) {
        $conn = mysqli_connect("localhost", "root", "test", "blog_samples");
        $query = "INSERT INTO tbl_users (userName, userEmail) VALUES ('" . $userName . "', '" . $userEmail . "')";
        mysqli_query($conn, $query);
        mysqli_close($conn);
    } else {
        $message = "All fields are required";
    }
}
?>

Download

This PHP code tutorial was published on May 18, 2013.

↑ Back to Top

Share this Article