PHP & MySQL: preventing SQL Injection
Overview:
SQL Injection is the act of someone causing a SQL statement to be executed on your database that you are unaware of. This could be as simple as modifying a query to return unexpected results or executing a query that could modify your database unexpectedly.
example:
Assume you have the below php code:
$query = " SELECT * FROM Users WHERE username = '$username'" AND password = '$password'";
Next lets see what would happen if
$username and password were set to ” ‘ OR ‘ ‘ = ‘ ”
The result would be the following SQL statement:
SELECT * FROM users WHERE username = '' OR ' ' = ' ' AND password = '' OR ' ' = ' ';
As you can see the this would return all Users from your database.
More harmfull attacks would be the injection of additonal SQL statments
lets assume
- $password= ” ; DELETE FROM Users WHERE 1 OR username = ‘ “
- $username = ” “;
In this case the following SQL would be executed:
SELECT * FROM users WHERE username = ' ' AND password = ' '; DELETE FROM Users WHERE 1 or username = ' ';
This would cause all the information in your Users table to be deleted.
Solution
To stop SQL Injection attacks you must in your code verify the information you pass to SQL statements. You can do this by escaping the information or making sure it contains only valid values.
In PHP this is easily enough done by using the mysql_real_escape_string() function. What this function does is escape the string so that even if it did contain harmfull information the escaping of characters would cause it to be treated as a string.
example:
$username = mysql_real_escape_string( $_POST['user_name'] );
$SQL = “SELECT * FROM Users WHERE username = ‘$username’”;
To be even more thorough it is good practice to verify the data before you pass it to the SQL Statement for example if you are expecting an integer make sure you have recieved an integer.
No comments yet. Be the first.
Leave a reply