

预处理语句针对SQL注入是非常有用的,因为参数值发送后使用不同的协议,保证了数据的合法性。预处理看作是想要运行的SQL的一种编译过的模板,它可以使用变量参数进行定制。 (推荐学习:PHP视频教程)
防御方法一
mysql_real_escape_string – 转义SQL 语句中使用的字符串中的特殊字符,并考虑到连接的当前字符集 !
$sql = "select count(*) as ctr from users where username ='".mysql_real_escape_string($username)."' and password='". mysql_real_escape_string($pw)."' limit 1";
方法二:
打开magic_quotes_gpc来防止SQL注入。php.ini中有一个设置:magic_quotes_gpc =
Off这个默认是关闭的,如果它打开后将自动把用户提交对sql的查询进行转换,比如把 ’ 转为 '等,对于防止sql注射有重大作用。
如果magic_quotes_gpc=Off,则使用addslashes()函数。
方法三:
自定义函数
function check_param($value=null) {
#select|insert|update|delete|\'|\/\*|\*|\.\.\/|\.\/|union|into|load_file|outfile
$str = 'select|insert|and|or|update|delete|\'|\/\*|\*|\.\.\/|\.\/|union|into|load_file|outfile';
if(!$value) {
exit('没有参数!');
}elseif(eregi($str, $value)) {
exit('参数非法!');
} return true;
}
function str_check( $value ) {
if(!get_magic_quotes_gpc()) {
// 进行过滤
$value = addslashes($value);
}
$value = str_replace("_", "\_", $value);
$value = str_replace("%", "\%", $value);
return $value;
}
function post_check($value) {
if(!get_magic_quotes_gpc()) {
// 进行过滤
$value = addslashes($value);
}
$value = str_replace("_", "\_", $value);
$value = str_replace("%", "\%", $value);
$value = nl2br($value);
$value = htmlspecialchars($value);
return $value;
}