Search code examples
phphtmlsymfony6

Cannot allow element (img: 'src') with symfony html-sanitizer (symfony6.3 php 8.2)


As per https://symfony.com/doc/current/html_sanitizer.html#allow-elements I created an html sanitizer implementation:

  • config/packages/html_sanitizer.yaml
framework:
    html_sanitizer:
        sanitizers:
            app.post_sanitizer:
                allow_safe_elements: true
                #allow_static_elements: true
                allow_elements:
                    img: '*'
                    #img: ['src', 'class']
                    span: '*'
                    p: 'class'
  • Controller/TestController.php
#[Route('/read_html', name: 'read_html')]
public function readHtml(HtmlSanitizerInterface $appPostSanitizer): Response {
$testHtml = '<div>
    <span style="font-size: 21pt;">This some big text</span>
    <img src="img_girl.jpg" alt="Girl in a jacket" width="500" height="600" class="img-fluid" >
    <p class="text-danger">this is some red text in bootstrap!</p>
</div>';
$testHtml2 = $appPostSanitizer->sanitize($testHtml);
dd($testHtml, $testHtml2);
    }
  • output:
"""
<div>
    <span style="font-size: 21pt;">This some big text</span>
    <img alt="Girl in a jacket" width="500" height="600" class="img-fluid" />
    <p class="text-danger">this is some red text in bootstrap!</p>
</div>
"""

i.e. everything else works except src in img tag.

src="img_girl.jpg" is missing.

I have tried any combination I could think of like :img: ['src', 'class'] img: 'src'. Still could not make src show up after sanitization.


Solution

  • You must set allow_relative_medias: true.

    When you set allow_relative_medias to true, you instruct the sanitizer to make an exception for relative URLs. Relative URLs are URLs that do not include the full web address and protocol (e.g., img_girl.jpg).

    Read more in the docs: https://symfony.com/doc/current/html_sanitizer.html#force-allow-media-urls