您好,欢迎访问一九零五行业门户网

php预防XSS攻击的一些方法整理

现在有很多php开发框架都提供关于防xss攻击的过滤方法,下面和大家分享一个预防xss攻击和ajax跨域攻击的函数,摘自某开发框架,相比于仅仅使用内置函数应该还是够强了的吧.
对网站发动xss攻击的方式有很多种,仅仅使用php的一些内置过滤函数是对付不了的,即使你将filter_var,mysql_real_escape_string,htmlentities,htmlspecialchars,strip_tags这些函数都使用上了也不一定能保证绝对的安全.
那么如何预防 xss 注入?主要还是需要在用户数据过滤方面得考虑周全,在这里不完全总结下几个 tips.
1. 假定所有的用户输入数据都是邪恶的 
2. 弱类型的脚本语言必须保证类型和期望的一致 
3. 考虑周全的正则表达式 
4. strip_tags、htmlspecialchars 这类函数很好用 
5. 外部的 javascript 不一定就是可靠的 
6. 引号过滤必须要重点注意 
7. 除去不必要的 html 注释 
8. exploer 求你放过我吧……
方法一,利用php htmlentities函数
例子:php防止xss跨站脚本攻击的方法:是针对非法的html代码包括单双引号等,使用htmlspecialchars()函数.
在使用htmlspecialchars()函数的时候注意第二个参数,直接用htmlspecialchars($string) 的话,第二个参数默认是ent_compat,函数默认只是转化双引号(),不对单引号(')做转义.
所以,htmlspecialchars函数更多的时候要加上第二个参数,应该这样用: htmlspecialchars($string,ent_quotes).当然,如果需要不转化如何的引号,用htmlspecialchars($string,ent_noquotes).
另外,尽量少用htmlentities,在全部英文的时候htmlentities和htmlspecialchars没有区别,都可以达到目的.但是,中文情况下,htmlentities却会转化所有的html代码,连同里面的它无法识别的中文字符也给转化了.
htmlentities和htmlspecialchars这两个函数对 '之类的字符串支持不好,都不能转化, 所以用htmlentities和htmlspecialchars转化的字符串只能防止xss攻击,不能防止sql注入攻击.
所有有打印的语句如echo,print等 在打印前都要使用htmlentities() 进行过滤,这样可以防止xss,注意中文要写出htmlentities($name,ent_noquotes,gb2312).
方法二,什么也不多说我们给一个函数,代码如下:
function xss_clean($data){ // fix &entity\n; $data=str_replace(array('&','<','>'),array('&amp;','&lt;','&gt;'),$data); $data=preg_replace('/(&#*\w+)[\x00-\x20]+;/u','$1;',$data); $data=preg_replace('/(&#x*[0-9a-f]+);*/iu','$1;',$data); $data=html_entity_decode($data,ent_compat,'utf-8'); // remove any attribute starting with on or xmlns $data=preg_replace('#(]+?[\x00-\x20\'])(?:on|xmlns)[^>]*+>#iu','$1>',$data); // remove javascript: and vbscript: protocols $data=preg_replace('#([a-z]*)[\x00-\x20]*=[\x00-\x20]*([`\']*)[\x00-\x20]*j[\x00-\x20]*a[\x00-\x20]*v[\x00-\x20]*a[\x00-\x20]*s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:#iu','$1=$2nojavascript...',$data); $data=preg_replace('#([a-z]*)[\x00-\x20]*=([\']*)[\x00-\x20]*v[\x00-\x20]*b[\x00-\x20]*s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:#iu','$1=$2novbscript...',$data); $data=preg_replace('#([a-z]*)[\x00-\x20]*=([\']*)[\x00-\x20]*-moz-binding[\x00-\x20]*:#u','$1=$2nomozbinding...',$data); // only works in ie: $data=preg_replace('#(]+?)style[\x00-\x20]*=[\x00-\x20]*[`\']*.*?expression[\x00-\x20]*\([^>]*+>#i','$1>',$data); $data=preg_replace('#(]+?)style[\x00-\x20]*=[\x00-\x20]*[`\']*.*?behaviour[\x00-\x20]*\([^>]*+>#i','$1>',$data); $data=preg_replace('#(]+?)style[\x00-\x20]*=[\x00-\x20]*[`\']*.*?s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:*[^>]*+>#iu','$1>',$data); // remove namespaced elements (we do not need them) $data=preg_replace('#]*+>#i','',$data); do{// remove really unwanted tags $old_data=$data; $data=preg_replace('#]*+>#i','',$data); }while($old_data!==$data); // we are done... return $data; }
本文地址:
转载随意,但请附上文章地址:-)
其它类似信息

推荐信息