Protection against SQL injection attacks in PHP.

Early on PHP had no good methods for escaping SQL, and until recently didn’t support parameterized queries. As a result a lot of documentation covers SQL queries without really addressing the issue, and a lot of older PHP developers are unaware of the enhancements made to prevent this type of attack.

PHP 4.3 introduced mysql_real_escape_string which escapes all potentially “bad” characters which could cause unwanted results in your queries. The link contains examples of how to use the function.

PHP5 includes the MySQLi (MySQL Improved) extention which provides a more enhanced API for accessing MySQL. The mysqli_stmt_bind_param function allows you to use parameterized queries. The link to the function provides an example of how to use parameterized queries.

Parameterized queries are generally considered safer than escaped strings, but that’s only in theory. mysql_real_escape_string currently escapes all known bad characters, and the only thing that would make it unsafe would be for another bad character to be discovered. But parameterized queries will go through a more complicated code path, and thus, more likely to be affected by a coding bug. So there’s really no security related argument which favors one over the other.

Leave a Reply