Friday, January 29, 2016

PHP: Use fiter_var() to sanitize data

PHP


filter_var In Action
filter_var will do, both, sanitize and validate data. What's the difference between the two?


  • Sanitizing will remove any illegal character from the data.
  • Validating will determine if the data is in proper form.

Note: why sanitize and not just validate? It's possible the user accidentally typed in a wrong character or maybe it was from a bad copy and paste. By sanitizing the data, you take the responsibility of hunting for the mistake off of the user.

How to use filter_var
Using filter_var is incredibly easy. It's simply a PHP function that takes two pieces of data:


  • The variable you want to check
  • The type of check to use

For example, the below code will remove all HTML tags from a string:

tring = "<h1>Hello, World!</h1>";
$new_string = filter_var($string, FILTER_SANITIZE_STRING);
// $new_string is now "Hello, World!"


$ip = "127.0.0.1";
$valid_ip = filter_var($ip, FILTER_VALIDATE_IP);
// $valid_ip is TRUE
$ip = "127.0.1.1.1.1";
$valid_ip = filter_var($ip, FILTER_VALIDATE_IP);

// $valid_ip is FALSE

That's how simple it is to use filter_var. For a complete list of all the rules you can check against, see the end of this tutorial. Sanitizing Example Below is a quick example of sanitizing input from two fields: an email field and a home page field. This example will remove any characters that should not occur in either type of data.

Then build the email message:

And finally, send the message:
However, if there were any errors, report them and have the user try again:
The completed project looks like this:

No comments:

Post a Comment