phpmysqlsql-injection

MySQL INJECTION Solution


I have been bothered for so long by the MySQL injections and was thinking of a way to eliminate this problem all together. I have came up with something below hope that many people will find this useful.

The only Draw back I can think of this is the partial search: Jo =>returns "John" by using the like %% statement.

Here is a php solution:

<?php
function safeQ(){
   $search= array('delete','select');//and every keyword...
   $replace= array(base64_encode('delete'),base64_encode('select'));
   foreach($_REQUEST as $k=>$v){
      str_replace($search, $replace, $v);
   }
}
safeQ();

function html($str){
   $search= array(base64_encode('delete'),base64_encode('select'));
   $replace= array('delete','select');//and every keyword...
   str_replace($search, $replace, $str);
}

//example 1
...
...
$result = mysql_fetch_array($query);
echo html($result[0]['field_name']);

//example 2
$select = 'SELECT * FROM $_GET['query'] '; 

//example 3
$insert = 'INSERT INTO .... value( $_GET['query'] )'; 


?>

I know, I know that you still could inject using 1=1 or any other type of injections... but this I think could solve half of your problem so the right mysql query is executed.

So my question is if anyone can find any draw backs on this then please feel free to comment here.

PLEASE GIVE AN ANSWER only if you think that this is a very useful solution and no major drawbacks are found OR you think is a bad idea all together...


Solution

  • Reinventing the wheel and reinventing it the Wrong Way (TM).

    Edit: To address the example you're giving in comments:

    $v="1; DROP tbl;\";DROP tbl" // oh look, an SQL injection attempt!
    $s = 'SELECT * FROM tbl WHERE ID='.$v; // SQL injection, no doubt
    
    // if ID is an integer field, make it an integer. Simple, secure, and fast.
    $s = 'SELECT * FROM tbl WHERE ID='.(int)$v; 
    // $s == 'SELECT * FROM tbl WHERE ID=1' // see PHP manual for explanation of type casting
    
    // if ID is a string field, escape it. Simple, secure, and still plenty fast.
    $s = 'SELECT * FROM tbl WHERE ID="'.mysql_real_escape_string($v) . '"';
    // $s == 'SELECT * FROM tbl WHERE ID="1; DROP tbl;\";DROP tbl"'; 
    // See? No injection, as the quote is *escaped*