Symfony6.3 HTML Sanitizer无法保留img标签的src属性问题
Symfony HTML Sanitizer 中 img 标签 src 属性被过滤的解决方案
核心原因
Symfony HTML Sanitizer 对 URI 类型的属性(比如 src)有严格的安全限制,默认不会直接允许所有来源的地址,必须显式配置信任的协议、域名或相对路径规则。
解决步骤
1. 修正 html_sanitizer.yaml 配置
确保配置中不仅允许 img 标签,还明确允许 src 属性,并配置对应的 URI 规则:
# config/packages/html_sanitizer.yaml framework: html_sanitizer: default: allow_elements: - img allow_attributes: img: ['src', 'alt', 'width', 'height'] # 允许的URI协议,根据需求调整(比如http/https/data) uri_schemes: ['http', 'https', 'data'] # 需要支持相对路径(如 /images/xxx.jpg)则开启此项 allow_relative_urls: true # 仅信任特定外部域名时,添加以下配置 allowed_hosts: ['your-domain.com', 'cdn.your-domain.com']
2. 检查 Controller 中的 Sanitizer 使用
确认正确注入并调用 Sanitizer,避免使用错误的配置实例:
// src/Controller/TestController.php namespace App\Controller; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HtmlSanitizer\HtmlSanitizerInterface; class TestController extends AbstractController { public function testSanitize(HtmlSanitizerInterface $sanitizer): Response { $dirtyHtml = '<img src="/images/test.jpg" alt="测试图片" width="200">'; $cleanHtml = $sanitizer->sanitize($dirtyHtml); return new Response($cleanHtml); } }
3. 排查特殊场景
- 如果使用 Data URI(比如
src="data:image/png;base64,..."),必须在uri_schemes中加入data; - 如果使用自定义命名的 Sanitizer(而非默认的
default),需要通过服务ID注入:use Symfony\Component\DependencyInjection\Attribute\Autowire; // ... public function testSanitize( #[Autowire(service: 'html_sanitizer.your_custom_sanitizer')] HtmlSanitizerInterface $sanitizer ): Response { // ... }
内容的提问来源于stack exchange,提问作者pok_net
相关产品推荐
相关产品推荐

