December 1, 2017

How to Validate (and Sanitize) User Input In PHP Using Filter_Input() and Filter_Var()

Never trust user data.

That’s the mantra. Good advice. So, how do you do it? In recording my newest training course, How to Submit and HTML Form to MySQL Using PHP, I talk quite a bit about the concept of “layered security”. Not my idea, though… it’s a pretty standard and accepted concept in application security (WikiPedia article on it here).

So, you have:

  • Prepared statements to stop SQL injection
  • Output escaping for XSS attacks
  • Tokens for CSRF

And, one I don’t see as much: input validation and sanitization using PHP’s filter_input() and filter_var() functions. So, you can do something like this:

<?php $name = filter_var($_POST['name'], FILTER_SANITIZE_STRING); ?>

That runs the $_POST element “name” through FILTER_SANITIZE_STRING… which “Strip tags, optionally strip or encode special characters.” You can see a full list of available filters here.

You can also validate like this:

<?php $email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL); ?>

Which will: “Validates whether the value is a valid e-mail address.” If it’s not a valid email address, filter_var() returns false meaning you can run validations checks off it, like this:

$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);

if ( $email === false ) {
 // Handle invalid emails here

Optionally, you can use filter_input() like this:

$name = filter_input(INPUT_POST, "name", FILTER_SANITIZE_STRING);
$email= filter_input(INPUT_POST, "email", FILTER_VALIDATE_EMAIL);
$search = filter_input(INPUT_GET, "s", FILTER_SANITIZE_STRING);

And, so on.

You also have filter_var_array() and filter_input_array() for filtering entire arrays at once WITH unique flags for each element.

In any case, do this to add just one more layer of security and ensure the user input you accept into your application isn’t going to let a hacker in the front door.

Also, if you’d like to learn preventing SQL injection and XSS attacks, as well, enroll in my new course. We go into all of it along with creating an HTML5 form, a MySQL database and tying the two together with PHP — in video format so you can see it come together. Plus, you get access to final source code to download and use as you wish.

2 Comments on “How to Validate (and Sanitize) User Input In PHP Using Filter_Input() and Filter_Var()

January 1, 2018 at 8:04 pm

Great article John, been looking for something like this for a while. I just joined your Udemy course, and it’s really good so far. Thanks, buddy.

John Morris
January 2, 2018 at 11:34 am

Thanks Mike! Glad you’re enjoying the course


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.