PHP MySQL tutorial

Validation and Sanitizing Data Via PHP Filters

In a previous article we studied how form validation is done in PHP. Apart from validating form fields, we often need to validate and sanitize data received from various sources. For instance we might want to check if the value enter by the user for price is in integer or not or email of a user is in valid format etc. The data that we want to check can be external such as received via cookies, or via web form as well as internal as server variables or result of a database query.

To validate and sanitize such data, PHP filters are used. Before digging deeper into the functionality of PHP filters, let us first differentiate between validation and sanitizing. Simply put, validating refers to the process of validating if the data is in correct format, while the sanitizing refers to cleaning of data by removing unwanted characters or letters. Let’s have a look at basic example of validation and sanitizing via PHP filters.

Welcome to Knowledge hills";
$sanitizedstr = filter_var($val, FILTER_SANITIZE_STRING);
echo $sanitizedstr. "
"; // Validating an integer $integer = 50; if (!filter_var($integer, FILTER_VALIDATE_INT) === false) { echo "This is a valid integer.
"; } else { echo "This is not a valid integer.
"; } ?>

Download the code
Run the code

In the above example the filter_var function is being used for validating and sanitizing data. This function takes two parameters: The first parameter is the data on which you want to perform validation or sanitizing. The second variable is the Filter option. For instance in the first example, the string is being sanitized by removing all the html tags around it. This is done by passing string to filter_var function as the first parameter. The second parameter is the FILTER_SANITIZE_STRING, this tells the function that it has to perform string sanitizing. Similarly to perform integer valdiation, FILTER_VALIDATE_INT option is used as the second parameter.

IP Email and URL validation

Have a look at the following example to see how PHP filters help validate an IP, Email and URL.

} else {
    echo("The ip $ipaddress is not a valid ip.
"); } // validating an email $id = ""; if (!filter_var($id, FILTER_VALIDATE_EMAIL) === false) { echo("The email $id is valid.
"); } else { echo("The email $id is not valid
."); } // validating a URL $address = ""; if (!filter_var($address, FILTER_VALIDATE_URL) === false) { echo("The address $address is a valid URL address."); } else { echo("The address $address is not a valid URL address."); } ?>

Download the code
Run the code

<<< Date and Time Functions in PHPIntroduction to Object Oriented Programming in PHP >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .