HTMLPurifier prevents XSS attacks in PHP

不言
Release: 2023-03-25 06:06:02
Original
1782 people have browsed it

This article introduces the content of HTMLPurifier in PHP to prevent XSS attacks. It has certain reference value. Now I share it with you. Friends in need can refer to it.

HTMLPurifier is the best I have ever used. The PHP rich text HTML filter adopts a whitelist mechanism, which effectively eliminates illegal HTML tags in user submission forms, thus preventing XSS attacks!

HTMLPurifier项目地址:http://htmlpurifier.org
Copy after login

Record the configuration method for use at work!

/**
 * 
 * @param  [type] $string [要过滤的内容]
 * @return [type]         [description]
 */function filterXSS($string){    //相对index.php入口文件,引入HTMLPurifier.auto.php核心文件
    require_once './Public/Admin/htmlpurifier/HTMLPurifier.auto.php';    // 生成配置对象
    $cfg = HTMLPurifier_Config::createDefault();    // 以下就是配置:
    $cfg -> set('Core.Encoding', 'UTF-8');    // 设置允许使用的HTML标签
    $cfg -> set('HTML.Allowed','p,b,strong,i,em,a[href|title],ul,ol,li,br,p[style],span[style],img[width|height|alt|src]');    // 设置允许出现的CSS样式属性
    $cfg -> set('CSS.AllowedProperties', 'font,font-size,font-weight,font-style,font-family,text-decoration,padding-left,color,background-color,text-align');    // 设置a标签上是否允许使用target="_blank"
    $cfg -> set('HTML.TargetBlank', TRUE);    // 使用配置生成过滤用的对象
    $obj = new HTMLPurifier($cfg);    // 过滤字符串
    return $obj -> purify($string);
}
Copy after login

HTMLPurifier's filtering function is very powerful. Here we mainly explain how to write the configuration. Only after the configuration is completed can we know how to expand it!

                                                                              ——用别人的微笑,点缀自己的生活,献给奋斗中的自己。
Copy after login

Related recommendations:

Using exec to call system commands in PHP

Using CURL in PHP Detailed analysis and common problems of php curl pit

The above is the detailed content of HTMLPurifier prevents XSS attacks in PHP. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!