如何 实现代码编辑状态下 安全过滤html标签

该方法解决了代码编辑状态下,提交时安全过滤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('[','&#091;',$text);
  $text=str_replace(']','&#093;',$text);
  $text=str_replace('|','&#124;',$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('<','&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;
}

//提交检查
function filter_result_check($text){
  $text=preg_replace('/ |&nbsp;|/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/

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值