半自动地为不安全的PHP mysql脚本添加安全性

I have a lot of files which have things like

1- mysql_query("update ... $_POST['foo'] ...");

I want to transform that to this

2- $foo = mysql_real_escape_string($_POST['foo']);
3- mysql_query("update ... $foo ...");

I had the idea to open each file, select the text $_POST['foo'] (form 1-) press a key combination, and then some tool automatically:

  • put on my clipboard mysql_real_escape_string($_POST['foo']); (for adding in 2-)
  • replace the text in 1- with the text in 3-

Then manually write $foo = and press ctrl+v to generate 2-

I'm trying with notepad++ and a plugin called fingertext, and trying to make a macro, but had no success.

Any suggestion?

$_POST = sanitize($_POST);
$_GET = sanitize($_GET);

    function sanitize($input) {
        if (is_array($input)) {
            foreach($input as $var=>$val) {
                $output[$var] = sanitize($val);
            }
        } else {
            if (get_magic_quotes_gpc()) {
                $input = stripslashes($input);
            }
            $output = mysql_real_escape_string($input);
        }
        return $output;
    }

It's not perfect, but if you have a lot of unsecure pages and need a quick fix to make them all secure, you can put this after connecting to mysql. also, keep in mind that if your query has unquoted numbers variables, you will have to either validate that they are numbers, or type cast them before using them in your query. mysql_real_escape_string() only works on quoted values (ie blah_column = 'value', but not blah_column = value).

Replace them one by one , with hand. If you care about security, dont make autoreplace. And also make a function at least instead of mysql_real_escape_string(() , use it.

 //just for example, better can be written
function db_escape($var, $type = 'string') 
{
   if($type == 'string') return mysql_real_escape_string($var);
   if($type == 'integer') return (int) $var;
   if($type == 'float') return (float) $var;
}