Tutorials MySQL MySQL Injections

MySQL Injections

Hi and welcome back to PHP Trainee. Today will be how to secure your database from injections. You already know what XSS and SMTP injections are. Now we have arrived at the most dangerous injection: SQL. Your database is your most valuable asset in your web server. You can attempt to hide your information in case of a security breach, but you shouldn't be in that situation in the first place. If hackers have access to your database, the battle is pretty much lost.

What are SQL injections?

SQL injections are when hackers try to insert their own code to access your database. They can login without a password or even get a full printout of your entire database if they're lucky.

How do SQL injections work?

SQL queries use information from the database. After a user posts their login information, you will probably grab the query and have something like:

$username = $_POST['username'];
$password = $_POST['password'];

$sql = 'SELECT * FROM users
  WHERE username = "'.$username.'" AND password = "'.$password.'"';
$result = mysql_query($sql);

If someone knows the username but doesn't know the password, they can jump out of your and comparison by putting in their own. Imagine if someone typed "OR""=" in the password field. Your query would turn into:

$sql = 'SELECT * FROM users
  WHERE username = "pete" AND password = ""OR""=""';
$result = mysql_query($sql);

The password comparison would return false but the "or" comparison would return true, thus making the whole thing true.

How do I protect against SQL injections?

This one line of code will protect you against 99% of attacks. It You need to escape the data before you allow it to touch the database.

$safe = mysql_real_escape_string($string);

Using mysql_real_escape_string escapes quotes with backslashes so hackers will be unable to jump out of your quotes. If anybody tries to enter quotes, it will turn into:

$sql = 'SELECT * FROM users
  WHERE username = "pete" AND password = "\"OR\"\"=\""';
$result = mysql_query($sql);

I escaped it but now I have unwanted backslashes

After you grab the data from your database, you can strip away the backslashes.

stripslashes($string);

That's it for this lesson. Now go back into your code and remove any vulnerbilities you may have. You should escape everything before entering it into the database.

Posted by on . Category: MySQL


Comments

No comments posted yet

You need to register or login to post new comments.