To use the sanitizer, you first create an HtmlSanitizerConfig object to define your security policy. The configuration uses a fluent interface to allow, block, or drop elements and attributes.
Key Configuration Concepts:
- Default Behavior: By default, any element not explicitly allowed or blocked is dropped, including its children.
- Element Management:
allowSafeElements(): Allows a predefined set of 'safe' elements and attributes (removes scripts and dangerous CSS).allowStaticElements(): Allows all static elements/attributes from the W3C Sanitizer API standard.allowElement(string $name, array|string $attributes): Allows a specific element. Use '*' to allow all attributes from the Sanitizer API.blockElement(string $name): Removes the element but retains its children.dropElement(string $name): Removes the element and drops its children.
- Attribute Management:
allowAttribute(string $name, array|string $targets): Allows an attribute on specific elements or globally using '*'.dropAttribute(string $name, array|string $targets): Removes a specific attribute.forceAttribute(string $element, string $attribute, string $value): Forces a specific value on an attribute (e.g., forcing rel="noopener noreferrer" on <a> tags).
- Link and Media Security:
- Control allowed schemes (e.g.,
https, http, mailto) using allowLinkSchemes() or allowMediaSchemes(). - Control allowed hosts using
allowLinkHosts() or allowMediaHosts(). - Enable relative URLs with
allowRelativeLinks() or allowRelativeMedias(). - Automatically upgrade links using
forceHttpsUrls().
- Custom Logic:
- Use
withAttributeSanitizer(AttributeSanitizerInterface $sanitizer) to apply custom sanitization logic to attributes.
use Symfony\Component\HtmlSanitizer\HtmlSanitizerConfig;
use Symfony\Component\HtmlSanitizer\HtmlSanitizer;
$config = (new HtmlSanitizerConfig())
->allowSafeElements()
->allowElement('a', ['title'])
->blockElement('section') // Removes section, keeps children
->dropElement('div') // Removes div and its children
->allowAttribute('data-custom-attr', '*')
->forceAttribute('a', 'rel', 'noopener noreferrer')
->allowLinkSchemes(['https', 'http'])
->allowRelativeLinks();
$sanitizer = new HtmlSanitizer($config);