这两天看了个防sql注入,觉得有必要总结一下:
首先需要做一些php的安全配置:
1 在php.ini 中把display_errors改成OFF
display_errors = OFF
或在php文件前加入
error_reporting(0)
2 关闭一些“坏功能”
1)关闭magic quotes功能
在php.ini 把magic_quotes_gpc = OFF
避免和addslashes等重复转义
2)关闭register_globals = Off
在php.ini 把register_globals = OFF
在register_globals = ON的情况下
3 使用过滤函数
Addslashes给这些 “‘”、“””、“\”,“NULL” 添加斜杆“\‘”、“\””、“\\”,“\NULL”, stripslashes则相反,这里要注意的是php.ini是否开启了magic_quotes_gpc=ON,开启若使用addslashes会出 现重复。所以使用的时候要先get_magic_quotes_gpc()检查
if(!get_magic_quotes_gpc()) { $abc = addslashes($abc); }
if (PHP_VERSION >= ‘4.3‘) { $string = mysql_real_escape_string($string); }else { $string = mysql_escape_string($string ); }
4 非文本参数的过滤
function _str_replace($str ) { $str = str_replace(" ","",$str); $str = str_replace("\n","",$str); $str = str_replace("\r","",$str); $str = str_replace("‘","",$str); $str = str_replace(‘"‘,"",$str); $str = str_replace("or","",$str); $str = str_replace("and","",$str); $str = str_replace("#","",$str); $str = str_replace("\\","",$str); $str = str_replace("-- ","",$str); $str = str_replace("null","",$str); $str = str_replace("%","",$str); //$str = str_replace("_","",$str); $str = str_replace(">","",$str); $str = str_replace("<","",$str); $str = str_replace("=","",$str); $str = str_replace("char","",$str); $str = str_replace("declare","",$str); $str = str_replace("select","",$str); $str = str_replace("create","",$str); $str = str_replace("delete","",$str); $str = str_replace("insert","",$str); $str = str_replace("execute","",$str); $str = str_replace("update","",$str); $str = str_replace("count","",$str); return $str; }