SQL Injection Prevention
What is SQL Injection?
SQL Injection is evil. Period. SQL Injection is where people gain access to your system using method unknown to you. Injection usually occur when you require the user to fill in a form, often in a form of a username or a password => They put something evil in the box and crashes your system. That evil something is of a form of a SQL statement and actively running their code onto your database.
Types of SQL Injection
There are 2 types: ones that gains access to your system (as an admin) and ones that corrupt your database.
First type:
1 2 3 4 5 | // user input that uses SQL Injection $injection_string = "' OR 1'"; // our MySQL query builder, however, NOT a very safe one $query_bad = "SELECT * FROM users WHERE username = '$injection_string'"; |
This will grant them unlimited power, since the OR 1 part always return true… evil….
Second Type:
1 2 3 4 | // user input that uses SQL Injection $injection_string = "'; DELETE FROM user WHERE 1 or username = '"; // our MySQL query builder, however, NOT a very safe one $query_bad = "SELECT * FROM users WHERE username = '$injection_string'"; |
This will destroy your database…
SQL Injection Prevention
SQL Injection is a common thing. Easy to try, easy to implement. out of a thousand people going to your website, would only 1 of them try if your application is secure or not? That’s why, it’s a common thing to prevent such an obvious security hole. All you need to do is apply the mysql_real_escape_string function to the thing.
1 2 3 | $injection_string = "'; DELETE FROM user WHERE 1 or username = '"; $query_ok = "SELECT * FROM users WHERE username = 'mysql_real_escape_string($injection_string)'"; |
and it will be ok, basically, they will replace all single quote and double quote character with the escaped string \’ and covered this security hole.
And due to the problem of PHP versions support, this function is not available in older versions of php… So this will do for all version
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | function prep($value){ $magic_quotes_active = get_magic_quotes_gpc(); $new_enough_php = function_exists( "mysql_real_escape_string" ); // i.e. PHP >= v4.3.0 if( $new_enough_php ) { // PHP v4.3.0 or higher // undo any magic quote effects so mysql_real_escape_string can do the work if( $magic_quotes_active ) { $value = stripslashes( $value ); } $value = mysql_real_escape_string( $value ); } else { // before PHP v4.3.0 // if magic quotes aren't already on then add slashes manually if( !$magic_quotes_active ) { $value = addslashes( $value ); } // if magic quotes are active, then the slashes already exist } return $value; } |