Wednesday, December 14, 2011

A Simple Method to Protect Your PHP Applications From SQL Injection Attacks

As a PHP developer, security within your applications is a top priority. Users expect you to know, understand, and implement security checks throughout your applications to help keep their sites safe.

One of the more popular types of attacks is an SQL injection attack. Wikipedia describes an SQL injection attack as:
A SQL injection is often used to attack the security of a website by inputting SQL statements in a web form to get a badly designed website to perform operations on the database (often to dump the database content to the attacker) other than the usual operations as intended by the designer. 
The key to stopping SQL injection attacks is to use  the mysql_real_escape_string() function to "clean" any user-inputted data before inserting it into your database.

But, applying mysql_real_escape_string to individually to each value you insert into your database can get a bit tedious... and, in the case of larger forms, a bit ridiculous.

Thankfully, you don't need. Using the method I'm about to show you, you can easily clean all your input data without the need to clean each value separately. Here's how:

Using array_map() to Efficiently Clean Input Data

As you know, whenever you collect data from an HTML form that data comes back to you in a $_POST array.You then process that $_POST array to insert the data in your database accordingly.

So, instead of cleaning each value individually, you can clean the entire $_POST array in one fell swoop using a lesser-known PHP function called array_map(). Here's how it looks:

function clean_data($array) {
          return array_map ( 'mysql_real_escape_string', $array );
}
$cleaned_data = clean_data($_POST);

What array_map does is apply the callback function, in this case mysql_real_escape_string, to every value in the passed array. So, we simply pass our entire $_POST array to our clean_data() function and we're all set.

A couple things to keep in mind when doing this. The mysql_real_escape_string function requires a MySQL connection already be established in order to work. So, you would call this function AFTER you've connected to MySQL in your code.

Also, SQL injection attacks aren't the only kind of attack and using mysql_real_escape_string isn't the only security measure you should implement. However, as the PHP manual itself says: "This function must always (with few exceptions) be used to make data safe before sending a query to MySQL."

Now, you have an easy way to do it. Be sure to let me know what you think and you find this useful for you!

Monday, December 12, 2011

Google+ Officially Integrates With Blogger... Uh, that's a big deal!

Soooo... Google+ just officially integrated with Blogger. Methinks this is a big deal. Jumping on this bandwagon early. First post. More to come... now, off to find a cool theme!