SQL Injection
Hey there! Welcome to Making the Web - my personal blog about website development. Feel free to subscribe to my RSS feed to keep up with the latest. Alternatively, subscribe by email. Hope you enjoy this article!
This article is provided for information only. Only use the information within this article to create "hacker-proof" applications.
SQL Injection is a way that hackers can execute SQL code, by exploiting a security vulnerability in an application. It allows hackers to get email addresses, passwords and other information from databases.
Before you include any input into a SQL query, the data should be correctly escaped.
Image a MySQL query, in PHP like this:
mysql_query('SELECT email FROM `users` WHERE username = "'.$_POST['username'].'" AND password = "'.$_POST['password'].'"');
If you are using input data like this in a query, then you have a huge security vulnerability with your website. Everything should be fine if $_POST['username'] and $_POST['username'] are something like these:
mike16 , password
But, image what would happen if $_POST['username'] and $_POST['password'] contained this:
none" OR "" = "
That input would make the query like this (input highlighted with bold):
mysql_query('SELECT email FROM `users` WHERE username = "none" OR "" = "" AND password = "none" OR "" = ""');
If this was a login form, a hacker would be able to access anyones account, without the need for their password or username. Once in their account, the hacker could get personal information, delete their account or edit it.
Luckily, there is a way to make the data safe before using it in a query. The input has to be escaped. With MySQL in PHP you can use the mysql_real_escape_string() function:
mysql_query('SELECT email FROM `users` WHERE username = "'.mysql_real_escape_string($_POST['username']).'" AND password = "'.mysql_real_escape_string($_POST['password']).'"');
If a hacker did then insert none" OR "" = " or something else, it would look similar to this:
mysql_query(SELECT email FROM `users` WHERE username = "none\" OR \"\" = \"" AND password = "none\" OR \"\" = \"");
This query is now safe, and, as you can see, it protects from SQL Injection.











