Injection flaws, particularly SQL injection, are common in web applications. Injection occurs when user-supplied data is submitted as part of a command or query. The attacker’s hostile data tricks the application into executing unintended commands or changing data.

Given this piece of code which inserts user input directly into a query

$sql = " SELECT fieldlist FROM table WHERE email = ’ $_POST[’ EMAIL ’]’ " ;

The developer is expecting the user to submit a valid email address. However, there is nothing stopping a malicious user from submitting a srting that entirely changes the query. Suppose the attacker submits x ’ or ’ x ’ = ’ x ’.

The query now becomes:

$sql = "SELECT fieldlist FROM table WHERE email = ’ x ’ or ’ x ’ = ’ x ’ ;

Since ’ x ’ = ’ x ’ is always true. The query will return every record in the table. This is a trivial example however this technique can be used to construct much more damaging queries.


Preventing injection requires keeping un-trusted data separate from commands and queries.

  • The preferred option is to use a safe API that avoids the use of the interpreter entirely or provides a parameterized interface.
  • If a parameterized API is not available, you should carefully escape special characters using the specific escape syntax for that interpreter (e.g. for MySQL use the mysql_real_escape_stringfunction).
  • Positive or white list input validation with appropriate canonicalization is also recommended, but is not a complete defense as many applications require special characters in their input.