Defending against SQL Injection attacks
First, let me just say that this is not a tutorial, this is an article meant to give you an overview with a few options thrown in.
Ok, let’s start …
You should protect your relational databases (like MySQL) from the dreaded SQL injection attack. These attacks are conducted by evil sniveling nerds, trying to insert damaging SQL code into your HTML form fields (and query strings too) to do things like … drop database tables or even wipe out your database altogether!
… These attacks are very real!
My Recent Experience
We recently put up our new shopping cart system … I personally keep on eye on activity, and to my surprise, we can get 25-30 attempted attacks a day! Man, if I could just get my hands on one of these guys ….
Fortunately, there are a few code-centric steps you can take to protect yourself from these SQL injection attacks:
- Use this function: mysql_real_escape_string() and wrap your input variables with it.
- Use an object-relational mapping (orm) system to basically avoid writing SQL to begin with. I hear the best one for PHP’rs today is Doctrine
- use a prepared statement that basically processes everything and cleans it up for you. PHP has the PDOStatement class for this.
Another option (that I like to use), is to just remove the database from any possible external interaction. Sometimes this is not possible but when it is, it works well. So for instance, our cart does not talk to a relational database at all, so all these SQL injection attacks we get just makes me giggle like a little school girl.