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

简介: 原文:PHP实例——输出安全的HTML代码 //输出安全的htmlfunction h($text, $tags = null){ $text = trim($text); //完全过滤注释 $text = preg_replace('//','',$t...
原文: 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('[','&#091;',$text);
$text = str_replace(']','&#093;',$text);
$text = str_replace('|','&#124;',$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;
}
目录
相关文章
|
1月前
|
前端开发
html空格代码怎么写
HTML中的空格可以通过多种方式实现,这取决于你想要在页面上显示的空格类型。以下是一些常用的方法来在HTML中创建空格
|
3月前
|
JavaScript
用什么代码可以在页面添加html元素呢?
用什么代码可以在页面添加html元素呢?
|
3月前
|
安全 JavaScript Go
Vue中的v-html指令有什么潜在的安全风险?如何防范?
Vue中的v-html指令有什么潜在的安全风险?如何防范?
166 1
|
7天前
|
前端开发
HTML代码示例
HTML代码示例
12 1
|
7天前
|
搜索推荐
当使用HTML代码时,一些常见的问题
当使用HTML代码时,一些常见的问题
7 0
|
8天前
错误或拦截页面的html代码
错误或拦截页面的html代码
12 0
错误或拦截页面的html代码
|
9天前
|
PHP
web简易开发——通过php与HTML+css+mysql实现用户的登录,注册
web简易开发——通过php与HTML+css+mysql实现用户的登录,注册
|
17天前
|
搜索推荐 前端开发 UED
html页面实现自动适应手机浏览器(一行代码搞定)
html页面实现自动适应手机浏览器(一行代码搞定)
18 0
|
1月前
当当网首页——html代码
当当网首页——html代码
8 1
|
1月前
网状的隧道穿梭特效HTML代码
网状的隧道穿梭特效HTML代码,效果是动态的,可以下载源码,自己在本地运行
12 0
网状的隧道穿梭特效HTML代码