12.3. Injection

Injection is where an attacker provides input to directly affect the execution of a command in his favor. I will actually talk about two types of injection attacks: SQL injection and command injection. This family of attacks can be quite devastating.

12.3.1. SQL Injection

The best way to explain SQL injection is jump right in with an illustration, so suppose you have a query, which should delete various records from the database that are older than a given date.

$query = 'DELETE FROM WROX_CALENDAR WHERE TSTAMP < "' . $_POST['date'] . '"';
mysql_query($query, $GLOBALS['DB']);

In the desired scenario a user will submit an appropriate date, for example 2007-12-20. This would expand the query to:


In this example, all events prior to December 20th would be deleted. However, what happens if the user were to enter the following string for the date value?

2007-12-20" OR 1=1 --

The query would then expand to:


Since a date is provided, records prior to December 20 would certainly be deleted, but the attacker injected extra information which found its way into query string: " OR 1=1 --. The double quote matches the opening quote prior to the date, but then another condition appears. Since a number equals itself this condition is always true. The final query would delete all records in the WROX_CALENDAR table. The trailing two dashes is how MySQL denotes ...

Get PHP and MySQL®: Create-Modify-Reuse now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.