rhukster / dom-sanitizer
一个简单但有效的PHP 7.4+ DOM/SVG/MathML Sanitizer
1.0.7
2023-11-06 16:46 UTC
Requires
- php: >=7.3
- ext-dom: *
- ext-libxml: *
Requires (Dev)
- phpunit/phpunit: ^9
README
一个简单但有效的PHP 7.3+ DOM/SVG/MathML Sanitizer。由于我对一个性能良好的DOM和特定于SVG的MIT兼容性Sanitizer的需求,因此创建了它。
它借鉴了出色的JavaScript库DOMPurify中的广泛有效的标签和属性列表,但使用PHP DOMDocument来解析DOM并过滤掉危险的标签和属性。
安装
composer require rhukster/dom-sanitizer
选项
选项可以作为可选数组传递给sanitize()
方法。默认值如下
$options = [ 'remove-namespaces' => false, 'remove-php-tags' => true, 'remove-html-tags' => true, 'remove-xml-tags' => true, 'compress-output' => true, ];
用法
清洗HTML
默认选项,提供完整的HTML标签和属性列表。
require 'vendor/autoload.php'; use Rhukster\DomSanitizer\DOMSanitizer; $input = file_get_contents('bad.html'); $sanitizer = new DOMSanitizer(DOMSanitizer::HTML); $output = $sanitizer->sanitize($input, [ 'remove-html-tags' => false, ]);
清洗SVG
您可以通过将DOMSanitizer::SVG
传递给构造函数来限制有效的标签和属性。如果您知道您正在处理SVG,这建议您这样做。
require 'vendor/autoload.php'; use Rhukster\DomSanitizer\DOMSanitizer; $input = file_get_contents('bad.svg'); $sanitizer = new DOMSanitizer(DOMSanitizer::SVG); $output = $sanitizer->sanitize($input);
清洗MathML
您可以通过将DOMSanitizer::MATHML
传递给构造函数来限制有效的标签和属性。如果您知道您正在处理MathML代码,这建议您这样做。
require 'vendor/autoload.php'; use Rhukster\DomSanitizer\DOMSanitizer; $input = file_get_contents('mathml-sample.xml'); $sanitizer = new DOMSanitizer(DOMSanitizer::MATHML); $output = $sanitizer->sanitize($input, [ 'compress-output' => false, ]);
修改允许的标签和属性
您可以通过以下方法完全访问标签和属性
public function addAllowedTags(array $allowed_tags): void public function addAllowedAttributes(array $allowed_attributes): void public function addDisallowedTags(array $disallowed_tags): void public function addDisallowedAttributes(array $disallowed_attributes): void public function getAllowedTags(): array public function setAllowedTags(array $allowed_tags): void public function getAllowedAttributes(): array public function setAllowedAttributes(array $allowed_attributes): void public function getDisallowedTags(): array public function setDisallowedTags(array $disallowed_tags): void public function getDisallowedAttributes(): array public function setDisallowedAttributes($disallowed_attributes): void