Don’t use addslashes for database escapes
November 30th, 2007 by Ivo
On a regular basis, I still encounter the following conversation:
"What do you do against SQL injection?"
"I escape the data."
This is not the best way to escape data. The most important reason is security. addslashes can lure you into a false sense of security. As Chris Shiflett points out, there are situations that addslashes doesn't escape.
Use mysql_real_escape_string instead.
When using a different database, such as Oracle, addslashes won't help either: the single quote escape for MySQL is ', but for oracle it's '' (a double single quote). For each database there is an alternative to mysql_real_escape_string.
An even better way to handle this problem is to use prepared statements, for example with PDO. PDO uses prepared statement capabilities of the database if supported, or emulates it when it isn't supported. In a prepared statement, it is a lot harder to exploit SQL injections.
Many people know about the disadvantages of addslashes, and it's even covered in the ZCE exam, but still a lot of people use addslashes. Probably one of the main reasons is that the documentation at php.net still states this:
An example use of addslashes() is when you're entering data into a database. For example, to insert the name O'reilly into a database, you will need to escape it. Most databases do this with a which would mean O'reilly."
The comments in the manual mention the problems, but many developers will not read those.
So even if this is old news, it's good to draw attention to it every once in a while.