typo3/html-sanitizer
Standards-based HTML sanitizer for PHP with safe, configurable cleaning of untrusted markup. Remove dangerous tags/attributes, normalize output, and allow whitelisting policies for links, images, and formatting—ideal for user content, CMS, and APIs.
Start by installing via Composer: composer require typo3/html-sanitizer. The core entry point is the HtmlSanitizer class—create a sanitized instance using one of the built-in policies (e.g., InlineContent, BlockContent, or RichText) or build a custom policy. For example:
use TYPO3\HtmlSanitizer\HtmlSanitizer;
use TYPO3\HtmlSanitizer\Policy\InlineContentPolicy;
$sanitizer = new HtmlSanitizer(new InlineContentPolicy());
$safeHtml = $sanitizer->sanitize($userInputHtml);
The InlineContentPolicy removes block-level tags and attributes, ideal for comments, captions, or short text fields. First use case: sanitizing user comments before rendering them on a public page.
BlockContentPolicy for CMS content areas, EmailPolicy for email bodies, RichTextPolicy for WYSIWYG editor inputs). This ensures minimal necessary permissions per use case.HtmlSanitizer in a custom SanitizeHtml facade or service—bind it via service provider for DI. Use a macroable string helper or middleware to sanitize request inputs automatically where needed.strip_tags() isn’t enough, use HtmlSanitizer in a custom SanitizeHtml rule to ensure HTML safety and permitted structure.data-* attributes support):class CustomPolicy extends BlockContentPolicy
{
public function getAttributesForElement(string $element): array
{
return array_merge(parent::getAttributesForElement($element), ['data-foo', 'data-bar']);
}
}
data-test not data-Test).disabled must be allowed explicitly in getBooleanAttributes() or getEmptyAttributes()—they’ll be stripped otherwise.<style> and <script> tags are always stripped, even if allowed—no exceptions. For dynamic styling, use class + CSS instead.getAllowedUrlProtocols()—http, https, mailto, and tel are safe defaults; javascript: is blocked by default.HtmlSanitizer::getSanitizedDomDocument() to inspect intermediate DOM after sanitization—helps track down why an element/attribute vanished.How can I help you explore Laravel packages today?