试图实现一个表单,根据www.example.com清理html输入https://symfony.com/doc/current/html_sanitizer.html#sanitizing-html-from-form-input,但我不能使它正常工作。以下是我的设置:
html_sanitizer.yaml
framework:
html_sanitizer:
sanitizers:
app.post_sanitizer:
allow_safe_elements: true
#allow_static_elements: true
allow_relative_medias: true
allowed_link_schemes: ['http', 'https', 'href']
allow_relative_links: true
allow_elements:
img: '*'
div: '*'
span: '*'
p: '*'
a: '*'
i: '*'
ActivityRichTextFormType.php
class ActivityRichTextFormType extends AbstractType
{
public function __construct(
private readonly HtmlSanitizerInterface $appPostSanitizer,
) {
}
public function buildForm(FormBuilderInterface $builder, array $options): void
{
//$data1 = $options['data']->getContent();
//$data1 = $this->appPostSanitizer->sanitize($data1);
//$options['data']->setContent($data1);
$builder->add('content', TextareaType::class,
['label' => '', 'empty_data' => '']
);
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'data_class' => ActRichText::class,
'sanitize_html' => true,
'sanitizer' => 'app.post_sanitizer',
'translation_domain' => false
]);
}
}
实体字段:
#[ORM\Column(type: Types::TEXT , nullable: true)]
#[Assert\Length(max: 2255)]
private ?string $content = null;
然后,为了测试功能,我输入类似于
<h2>Testing html form</h2>
<script>// <![CDATA[
(function(i,s,o,g,r,a,m){var ql=document.querySelectorAll('A[quiz],DIV[quiz]');
// ]]></script>
当我在解析器中使用'sanitize_html' => true, 'sanitizer' => 'app.post_sanitizer',
时,html文本不会被清理。即,脚本标签被保持在内容中。
作为一个临时的解决办法,我添加了一个手动消毒剂:
$data1 = $options['data']->getContent();
$data1 = $this->appPostSanitizer->sanitize($data1);
$options['data']->setContent($data1);
当我删除注解并激活此解决方案时,html确实得到了清理,脚本标记被删除。
有什么提示为什么resolver
中的sanitize_html
不工作?
谢谢你,谢谢
更新:
创建了一个全新的项目来测试此问题,并将其上传到github symfony-html-sanitizer。
我使用了模型而不是实体来简化事情,如果有人想看看的话。
1条答案
按热度按时间ecfdbz9o1#
$sanitizedInput = htmlspecialchars($_POST输入'inputField'],ENT_QUOTES,'UTF-8');
return($sanitizedInput,ENT_QUOTES,'UTF-8');
var cleanHTML = DOMPurify.sanitize(dirtyHTML);