How to Protect Against SQL Injection

One of the most common web security problems is SQL Injection. As the name implies, SQL injections works by introducing malicious SQL code where it doesn’t belong. Since it is SQL code you could probably guess that the attacker “injects” his poison via database queries. Web developers often pass some sort of variable to their database queries. Very common are variables that are influenced by user input. User input, to variable, then to query,- get it? So, there is a need for a way of eliminating the user’s ability to manipulate the variable in any way that could effect the query.

What Happens With SQL Injection

By passing an unexpected string of code into a user input, such a form, an attacker send damaging code that causes an otherwise good query to go haywire. For example:

unprotected query is vulnerable
unprotected query is vulnerable

The above snippet of code works as long as users put in the expected information. An attacker, will instead, make clever use of a few extra characters. You likely know by now that SQL requires a semi-colon at the end of each query. PHP automatically adds it in if you omit it. Because of this, the attacker, by closing the string and using the closing parenthesis to finish the query followed by a semi colon, can add an additional query to drop the table.example of SQL Injection

example of SQL Injection

This is what we in the world of secure web development refer to as a ‘bad thing’!
Scary isn’t it? Attackers have used this method to not only drop tables and destroy records, but also to retrieve highly sensitive information.

How to Protect Against SQL Injection

OK, after that scary bit of information, you’ll be glad to know that protecting yourself is really not all that hard. The hard part is always remembering when and where to do it.

Protecting against SQL Injection is a simple matter of calling a PHP function that renders data safe ( or cleansed ) for use in a query. There are a few methods for cleansing user input in PHP depending on the PHP extension you are using. We will be discussing the mysql extension.The name of the function is:
mysql_real_escape_string(). Notice in this snippet how it is used:

How to protect again SQL Injection
How to protect again SQL Injection

See how easy it is?  Just take the user input (in this case a post ) and pass it through the mysql_real_escape_string() function, (as shown on line 7 ). Then use the “cleansed” variable in the query ( as shown on line 9 ).

It is so easy to protect against this, yet it is often overlooked or forgotten. SO remember to use mysql_real_escape_string() to cleanse your input to help guard against SQL Injection.

There is more to learn and be discussed so feel free to stop back or drop me any suggestions or tips to share.

Leave a Reply

Your email address will not be published.