PHP函数用字符代码替换符号以停止SQL注入

Jos*_*ren 1 php mysql symbols sql-injection character-encoding

我正在尝试编写一个php函数来阻止MySQL注入尝试.我正在做的是使用str_replace()删除符号并用它们的HTML字符代码替换它们.我的问题是代码都包含&#; 但我也想用他们的代码替换这些符号.如何在不将代码更改为以下内容的情况下执行此操作:

&#38&#59;&338&#59;#35&#59;32&#59;
Run Code Online (Sandbox Code Playgroud)

这是我的功能:

function replaceSymbols( $text )
{
   $text = str_replace( '#', '&#35', $text );
   $text = str_replace( '&', '&' $text ); 
   $text = str_replace( ';', '&#59', $text );

   $text = str_replace( ' ', ' ' $text );
   $text = str_replace( '!', '!' $text );
   $text = str_replace( '"', '"' $text );   
   $text = str_replace( '$', '$' $text );
   $text = str_replace( '%', '%' $text );  
   $text = str_replace(  "'" '&#39', $text );
   $text = str_replace( '(', '(' $text );
   $text = str_replace( ')', ')' $text );
   $text = str_replace( '*', '*' $text );   
   $text = str_replace( '+', '&#43', $text );
   $text = str_replace( ',', ',' $text );
   $text = str_replace( '-', '-' $text );
   $text = str_replace( '.', '.' $text );   
   $text = str_replace( '/', '&#47', $text );
   $text = str_replace( ':', ':' $text );   
   $text = str_replace( '<', '&#60;' $text );
   $text = str_replace( '=', '&#61;' $text );
   $text = str_replace( '>', '&#62;' $text );   
   $text = str_replace( '?', '&#63', $text );
   $text = str_replace( '[', '&#91', $text );
   $text = str_replace( '\\', '&#92;' $text );
   $text = str_replace( ']', '&#93;' $text );
   $text = str_replace( '^', '&#94;' $text );   
   $text = str_replace( '_', '&#95', $text );
   $text = str_replace( '`', '&#96', $text );
   $text = str_replace( '{', '&#123;' $text );
   $text = str_replace( '|', '&#124;' $text );   
   $text = str_replace( '}', '&#125', $text );
   $text = str_replace( '~', '&#126', $text );

   return $text;

}
Run Code Online (Sandbox Code Playgroud)

And*_*are 11

你看过了mysql_real_escape_string吗?

转义未转义字符串中的特殊字符,同时考虑连接的当前字符集,以便将其放在mysql_query()中是安全的.

  • 当你开始思考自己,"自我,这是一个常见问题......"然后答案通常是"使用库函数!" 这就是他们在那里的原因.除非另有说服,否则你应该假设库函数会更好,更快,更安全,更便宜(代码等). (2认同)