one idea i had was to check the string for common words/phrases that are used in an sql injection which are never used in the application running the queries. If found, don't run the query and alert the admins.
Extremely bad idea.
The solution is to use PDO: http://php.net/manual/en/ref.pdo-mysql.php
And pass all $vars using parameters.
If you have to use dynamic SQL, make sure you check your injected stuff against a whitelist.
See this question on how to safely do that: How to prevent SQL injection with dynamic tablenames?
Now you are save.
If you cannot use PDO, use mysql_real_escape_string()
.
Here's an example:
$var = mysql_real_escape_string($_POST['unsafe_value']);
$query = "SELECT * FROM user WHERE username = '$var' ";
// The quotes are vital, without them ^ ^
//you will may get syntax errors and mysql_real.... will not protect you!
You can only use this for parameters not for table, column, database names or SQL constructs, also remember to always quote your '$vars'
.
For anything but values you must use whitelisting.
Note that addslashes
does not work and should not be used!
For integer values you can use intval(), but I advice against it, it saves no time, makes your code harder to read and it breaks the rule to always use mysql_real_escape_string()
.