Close

February 10, 2017

Simple input filtering in PHP

Here’s one I don’t see talked about much:

$name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING);

What this does is grab the “name” element from your POST array and run it through the the filter: FILTER_SANITIZE_STRING… which removes all HTML tags from the string (since we know a person’s name doesn’t have HTML in it).

It’s a really simple way of quickly filtering your data.

Here’s another:

if ( ! $email = filter_input( INPUT_POST, 'email', FILTER_VALIDATE_EMAIL ) ) {
 die('Invalid email');
}

This one validates the submitted email address.

And, returns false if it’s invalid.

Again, a very simple way of quickly validating your data.

And, there’s a roughly 20-30 different filters you can run your data through. Things like: FILTER_VALIDATE_URL, FILTER_VALIDATE_INT, FILTER_SANITIZE_SPECIAL_CHARS, FILTER_SANITIZE_EMAIL and more.

The idea here is:

  1. Filter data like this on input
  2. Escape it on submission to MySQL
  3. Escape it on output to the browser

That little routine will help you prevent invalid data, SQL injection, XSS attacks and whole host of other problems.

Anyway, it’s one of the things I show you in Module 3 of PHP 101. Along with, of course: CRUD basics, PDO, MySQLi, Prepared Statements… plus building a database class AND submitting HTML form data to MySQL using all of this.

Use this link to get the details on the course and grab Modules 1-3: http://www.johnmorrisonline.com/php

Later,

John


Also published on Medium.