yii2防止xss攻擊的示例代碼:
在對應文件中添加以下代碼進行調用:
/* 防sql注入,xss攻擊*/
function actionClean($str)
{
$str=trim($str);
$str=strip_tags($str);
$str=stripslashes($str);
$str=addslashes($str);
$str=rawurldecode($str);
$str=quotemeta($str);
$str=htmlspecialchars($str);
//去除特殊字符
$str=preg_replace("/\/|\~|\!|\@|\#|\\$|\%|\^|\&|\*|\(|\)|\_|\+|\{|\}|\:|\<|\>|\?|\[|\]|\,|\.|\/|\;|\'|\`|\-|\=|\\\|\|/", "" , $str);
$str=preg_replace("/\s/", "", $str);//去除空格、換行符、制表符
return $str;
}
//防止sql注入
public function actionFilterArr($arr)
{
if(is_array($arr)){
foreach($arr as $k => $v){
$arr[$k] = $this->actionFilterWords($v);
}
}else{
$arr = $this->actionFilterWords($arr);
}
return $arr;
}
//防止xss攻擊
public function actionFilterWords($str)
{
$farr = array(
"/<(\\/?)(script|i?frame|style|html|body|title|link|meta|object|\\?|\\%)([^>]*?)>/isU",
"/(<[^>]*)on[a-zA-Z]+\s*=([^>]*>)/isU",
"/select|insert|update|delete|drop|\'|\/\*|\*|\+|\-|\"|\.\.\/|\.\/|union|into|load_file|outfile|dump/is"
);
$str = preg_replace($farr,'',$str);
return $str;
}
//防止sql注入,xss攻擊(2)
public function post_check($post) {
if(!get_magic_quotes_gpc()) {
foreach($post as $key=>$val){
$post[$key] = addslashes($val);
}
}
foreach($post as $key=>$val){
//把"_"過濾掉
$post[$key] = str_replace("_", "\_", $val);
//把"%"過濾掉
$post[$key] = str_replace("%", "\%", $val); //sql注入
$post[$key] = nl2br($val);
//轉換html
$post[$key] = htmlspecialchars($val); //xss攻擊
}
return $post;
}