rhukster/dom-sanitizer
PHP 7.3+ DOM/SVG/MathML sanitizer using DOMDocument and DOMPurify-based allowlists. Removes dangerous tags/attributes, with options for namespace/PHP/HTML/XML stripping and output compression. Customize allowed/disallowed tags and attributes.
DOMDocument and integrates seamlessly with Laravel’s service container, middleware, and validation pipelines. The package’s stateless design allows for clean abstraction into Laravel-specific components (e.g., custom validation rules, request filters, or model events).SanitizedString rule).Post::accessors(['sanitized_content'])).@sanitize($html)).strip_tags for complex HTML/SVG/MathML, reducing false positives/negatives. Aligns with Laravel’s emphasis on explicit, auditable security practices.addAllowedTags() and setAllowedAttributes() enable fine-grained control, critical for Laravel apps with niche requirements (e.g., whitelisting SVG filters for a design tool).setAllowedTags()).<filter>, <animate>).config/sanitizer.php?Log::debug()).SanitizationException or return fallback content)?htmlspecialchars) should be replaced first?SanitizeInputMiddleware).SanitizedString extending String).DOMSanitizer instance configured via Laravel’s AppServiceProvider.@sanitize directive for templates.saving or updating.upload-avatar endpoint).application/json with HTML fragments).php artisan sanitize:backfill).strip_tags(), htmlspecialchars(), or custom regex.DOMDocument without validation).composer.json:
composer require rhukster/dom-sanitizer:^1.0.9
DOMSanitizer in AppServiceProvider:
$this->app->singleton(DOMSanitizer::class, function ($app) {
return new DOMSanitizer(DOMSanitizer::HTML);
});
use Rhukster\DomSanitizer\DOMSanitizer;
class SanitizedString extends String
{
public function validateAttribute($attribute, $value, $fail)
{
$sanitizer = app(DOMSanitizer::class);
$sanitized = $sanitizer->sanitize($value);
$this->requireAttributeNotEmpty($attribute, $sanitized, $fail);
}
}
// For SVG avatars
$avatarSanitizer = new DOMSanitizer(DOMSanitizer::SVG);
$avatarSanitizer->addAllowedAttributes(['fill', 'stroke-width']);
$sanitizer->addAllowedTags(['feGaussianBlur', 'feColorMatrix']);
// Example Artisan command
public function handle()
{
$posts = Post::whereNotNull('content')->get();
foreach ($posts as $post) {
$sanitizer = app(DOMSanitizer::class);
$post->sanitized_content = $sanitizer->sanitize($post->content);
$post->save();
}
}
laravel/framework, spatie/laravel-medialibrary).Cache::remember() for repeated sanitization).How can I help you explore Laravel packages today?