首页 技术 正文
技术 2022年11月15日
0 收藏 564 点赞 2,272 浏览 1946 个字

原文:PHP实例——输出安全的HTML代码

//输出安全的html
function h($text, $tags = null){
$text = trim($text);
//完全过滤注释
$text = preg_replace('/<!--?.*-->/','',$text);
//完全过滤动态代码
$text = preg_replace('/<\?|\?'.'>/','',$text);
//完全过滤js
$text = preg_replace('/<script?.*\/script>/','',$text);

$text = str_replace('[','[',$text);
$text = str_replace(']',']',$text);
$text = str_replace('|','|',$text);
//过滤换行符
$text = preg_replace('/\r?\n/','',$text);
//br
$text = preg_replace('/<br(\s\/)?'.'>/i','[br]',$text);
$text = preg_replace('/(\[br\]\s*){10,}/i','[br]',$text);
//过滤危险的属性,如:过滤on事件lang js
while(preg_match('/(<[^><]+)( lang|on|action|background|codebase|dynsrc|lowsrc)[^><]+/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);
}
if(empty($tags)) {
$tags = 'table|td|th|tr|i|b|u|strong|img|p|br|div|strong|em|ul|ol|li|dl|dd|dt|a';
}
//允许的HTML标签
$text = preg_replace('/<('.$tags.')( [^><\[\]]*)>/i','[\1\2]',$text);
//过滤多余html
$text = preg_replace('/<\/?(html|head|meta|link|base|basefont|body|bgsound|title|style|script|form|iframe|frame|frameset|applet|id|ilayer|layer|name|script|style|xml)[^><]*>/i','',$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('<','&lt;',$text);
$text = str_replace('>','&gt;',$text);
$text = str_replace('"','&quot;',$text);
//反转换
$text = str_replace('[','<',$text);
$text = str_replace(']','>',$text);
$text = str_replace('|','"',$text);
//过滤多余空格
$text = str_replace(' ',' ',$text);
return $text;
}
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,078
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,553
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,402
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,177
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,814
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,898