PHP防SQL注入,防挂马、防跨站攻击

SQL注入攻击,是攻击者在表单或地址栏中提交精心构造的sql语句,改动原来的sql语句,如果程序没有对提交的数据经过严格检查,那么就会造成sql注入攻击。
    SQL注入因为要操作数据库,所以一般会查找SQL语句关键字:insert、delete、update、select,查看传递的变量参数是否用户可控制,有无做过安全处理。

    防止SQL注入攻击的一些函数:

/**
+----------------------------------------------------------
* 防挂马、防跨站攻击、防sql注入函数
+----------------------------------------------------------
*$date 传入的参数,要是个变量或者数组;$ignore_magic_quotes变量的魔术引用
+----------------------------------------------------------
*/
function in($data,$ignore_magic_quotes=false)
{
	if(is_string($data))
	{
		$data=trim(htmlspecialchars($data));//防止被挂马,跨站攻击
		if(($ignore_magic_quotes==true)||(!get_magic_quotes_gpc())) 
		{
		   $data = mysql_real_escape_string($data);//防止sql注入
		}
		return  $data;
	}
	else if(is_array($data))//如果是数组采用递归过滤
	{
		foreach($data as $key=>$value)
		{
			 $data[$key]=in($value);
		}
		return $data;
	}
	else 
	{
		return $data;
	}	
}
再帖个函数,防别人留html和iframe的
function html_in($str)
{
	$search = array ("'<script[^>]*?>.*?</script>'si",  // 去掉 javascript
					 "'<iframe[^>]*?>.*?</iframe>'si", // 去掉iframe
					);
	$replace = array ("",
					  "",
					);			  
   $str=@preg_replace ($search, $replace, $str);
   $str=htmlspecialchars($str);
   	if(!get_magic_quotes_gpc()) 
	{
  	  $str = addslashes($str);
	}
   return $str;
}
discuz的php防止sql注入函数:
$magic_quotes_gpc = get_magic_quotes_gpc();
@extract(daddslashes($_COOKIE));
@extract(daddslashes($_POST));
@extract(daddslashes($_GET));
if(!$magic_quotes_gpc) {
$_FILES = daddslashes($_FILES);
}
 
 
function daddslashes($string, $force = 0) {
if(!$GLOBALS['magic_quotes_gpc'] || $force) {
if(is_array($string)) {
foreach($string as $key => $val) {
$string[$key] = daddslashes($val, $force);
}
} else {
$string = addslashes($string);
}
}
return $string;
}

你可能感兴趣的:(PHP防SQL注入,防挂马、防跨站攻击)