Don't trust user data


Too cute!

Two things here. First, users make honest mistakes. Someone mistypes a product name, a price, or whatevs. You can have your program catch errors, before they pollute the app's database. Well, catch some errors, anyway.

Validation is a Big Deal in this course. There's an entire section on it, patterns for single and multiple fields, and other stuff.

There's a second reason to not trust user data: hacking. Entering strange data is one way people break into systems.

Suppose we're grabbing an id from GET, and using it to lookup a DB record. For example:

  • $id = $_GET['id'];

We could insert $id directly into a string, to make a query:

  • $sql = "SELECT * FROM wombats WHERE wombat_id = $id;";

Easy enough, but that might leave the door open for hackers. Suppose a hacker typed:

  • ...?id=3;DELETE * FROM wombat;

The SQL we'd run:

  • SELECT * FROM wombats WHERE wombat_id = 3;DELETE * FROM wombat;

Wombat data gone! Not so good.

That's an SQL injection attack. It's the subject of a famous XKCD cartoon.

SQL injection

We use PHP's PDO library in this course. PDO sanitizes for you.

Where referenced