该方法解决了代码编辑状态下,提交时安全过滤html标签
<?php
$_POST['content']=filter_mark($_POST['content']); //content为提交的表单的textarea名
//服务器端检验
if(filter_result_check($_POST['content'])==''){
echo '提交被拒绝!——您并未输入有效的文本内容!<br><br>原因:你未输入内容,或只输入了空格、空html标签等。请<a href="javascript:window.history.back();">返回</a>';
}else{
echo $_POST['content'];
}
/* 过滤表单content 函数程序 */
function filter_mark($text){
$text=trim($text);
$text=stripslashes($text);
$text=str_replace('[','[',$text);
$text=str_replace(']',']',$text);
$text=str_replace('|','|',$text);
//过滤换行符
$text=preg_replace('//r?/n/','',$text);
//过滤动态代码
$text=preg_replace('/</?|/?>/','',$text);
//过滤隐藏域
$text=preg_replace('/<!--|-->/','',$text);
//过滤多余html
$text=preg_replace('/<//?(html|head|meta|link|base|body|title|style|script|form|iframe|frame|frameset)[^><]*>/i','',$text);
//过滤on事件 id name class lang js
while(preg_match('/(<[^><]+)( id| name| lang| class|onfinish|onmouse|onexit|onerror|onclick|onkey|onload|onchange|onfocus|onblur)[^><]+/i',$text,$mat)){
$text=str_replace($mat[0],$mat[1],$text);
}
while(preg_match('/(<[^><]+)(window/.|javascript:|js:|about:|file:|document/.|vbs:|cookie)([^><]*)/i',$text,$mat)){
$text=str_replace($mat[0],$mat[1].$mat[3],$text);
}
//br
$text=preg_replace('/<br(/s//)?>/i','[br]',$text);
$text=preg_replace('/(/[br/]/s*){10,}/i','[br]',$text);
//hr img area input
$text=preg_replace('/<(hr|img|input|area|isindex)( [^></[/]]*)>/i','[/1/2]',$text);
//过滤合法的html标签
while(preg_match('/<([a-z]+)[^></[/]]*>[^><]*<///1>/i',$text,$mat)){
$text=str_replace($mat[0],str_replace('>',']',str_replace('<','[',$mat[0])),$text);
}
//转换引号
while(preg_match('/(/[[^/[/]]*=/s*)(/"|/')([^/2=/[/]]+)/2([^/[/]]*/])/i',$text,$mat)){
$text=str_replace($mat[0],$mat[1].'|'.$mat[3].'|'.$mat[4],$text);
}
//过滤错误的单个引号
while(preg_match('//[[^/[/]]*(/"|/')[^/[/]]*/]/i',$text,$mat)){
$text=str_replace($mat[0],str_replace($mat[1],'',$mat[0]),$text);
}
//转换其它所有不合法的 < >
$text=str_replace('<','<',$text);
$text=str_replace('>','>',$text);
$text=str_replace('"','"',$text);
//反转换
$text=str_replace('[','<',$text);
$text=str_replace(']','>',$text);
$text=str_replace('|','"',$text);
//过滤多余空格
$text=str_replace(' ',' ',$text);
return $text;
}
//提交检查
function filter_result_check($text){
$text=preg_replace('/ | |/r?/n|<br(/s//)?>/i','',$text);
while(preg_match('/<([a-z]+)[^><]*>([^><]*)<///1>/i',$text,$mat)){
$text=str_replace($mat[0],$mat[2],$text);
}
return $text;
}
?>
具体应用参见:http://www.162100.com/forum/