PHP PDO, Prepared Statements, And Security

A long time ago, PHP used to be known as the language that was insecure. The reason why it was known that way is because it was very easy to write insecure code. In this lesson plan, we'll learn how to mitigate some of the major security vulnerabilities that exist so that you feel confident writing code.

One reason why it was easy to write insecure code was because the way that PHP used to handle database code. You used to have to mix data and queries together. This made it impossible for PHP and MySQL to understand the difference between what was query and what was data. This led to a major security vulnerability called SQL Injection Attacks.

If you'd like examples of how to test SQL Injection Attacks, use this link.

One of the easiest ways to prevent SQL Injection attacks is to use PHP PDO and it's prepared statements. This helps us create queries which separate query from data. This separation makes security much simpler for the developer.

Prepared statements can be difficult at times, but this guide will help you route around any difficulties and show you solutions that help make things work properly and easily.

When using prepared statements with data that comes from untrusted sources, ie: "the user", we use placeholders in our queries. These placeholders tell MySQL what is data and what is query.

Placeholders are simple to use and start with a colon and contain any text afterwards. Here are some examples of placeholders:

:id
:name
:page

Instead of directly placing untrusted data into the query, we use placeholders that allow MySQL to differentiate between query and data. That differentiation is the key to more application security and peace of mind.