Recently tested XSS attack fix, found a relatively good article, share to everyone.
Update20151202:
Thank you for your attention and answer, at present I learned from various ways of defense methods, organized as follows:
PHP directly output HTML, you can use the following methods to filter:
5 |
3.HTMLPurifier.auto.php插件 |
PHP output to the JS code, or the development of the JSON API, you need to filter the front-end in JS:
1 |
1.尽量使用innerText(IE)和textContent(Firefox),也就是jQuery的text()来输出文本内容 |
3 |
2.必须要用innerHTML等等函数,则需要做类似php的htmlspecialchars的过滤(参照@eechen的答案) |
Other general complementary defense methods
01 |
1.在输出html时,加上Content Security Policy的Http Header |
03 |
(作用:可以防止页面被XSS攻击时,嵌入第三方的脚本文件等) |
06 |
2.在设置Cookie时,加上HttpOnly参数 |
08 |
(作用:可以防止页面被XSS攻击时,Cookie信息被盗取,可兼容至IE6) |
09 |
(缺陷:网站本身的JS代码也无法操作Cookie,而且作用有限,只能保证Cookie的安全) |
11 |
3.在开发API时,检验请求的Referer参数 |
14 |
(缺陷:IE或低版本的浏览器中,Referer参数可以被伪造) |
4. Add an XSS filter function.
01 |
function clean_xss(& $string , $low = False) |
03 |
if (! is_array ( $string )) |
05 |
$string = trim ( $string ); |
06 |
$string = strip_tags ( $string ); |
07 |
$string = htmlspecialchars ( $string ); |
[ |
; $string = str_replace < Code class= "Brush Plain" ( array ( ", $string |
14 |
$string = preg_replace ( $no , ‘‘ , $string ); |
16 |
$string = preg_replace ( $no , ‘‘ , $string ); |
17 |
$no = ‘/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]+/S‘ ; |
18 |
$string = preg_replace ( $no , ‘‘ , $string ); |
21 |
$keys = array_keys ( $string ); |
22 |
foreach ( $keys as $key ) |
24 |
clean_xss ( $string [ $key ] ); |
The ultimate solution for PHP defense against XSS attacks