rhukster/dom-sanitizer
MIT-licensed PHP 7.3+ DOM/SVG/MathML sanitizer using DOMDocument and DOMPurify-based allowlists. Remove dangerous tags/attributes, strip namespaces and PHP/HTML/XML tags, and optionally compress output. Supports HTML, SVG, and MathML modes.
DOMDocument usage (e.g., in Blade templates or API responses).app/Http/Middleware/SanitizeSVG).UploadService::sanitizeSVG()).app/Concerns/SanitizesXML).Str::of() or htmlspecialchars).DOMDocument, reducing abstraction overhead. Example:
use Rhukster\DomSanitizer\DOMSanitizer;
class SVGUploader {
public function sanitize(string $svgContent): string {
$sanitizer = new DOMSanitizer(DOMSanitizer::SVG);
return $sanitizer->sanitize($svgContent, [
'remove-namespaces' => true, // Laravel-specific tweak
]);
}
}
namespace App\Http\Middleware;
use Rhukster\DomSanitizer\DOMSanitizer;
class SanitizeXML {
public function handle($request, Closure $next) {
if ($request->isXml()) {
$sanitizer = new DOMSanitizer(DOMSanitizer::HTML);
$request->merge(['content' => $sanitizer->sanitize($request->content)]);
}
return $next($request);
}
}
LIBXML_NONET, libxml_disable_entity_loader), but custom XML schemas/DTDs may still pose risks if not pre-processed.feGaussianBlur in 1.0.9).path, polygon, and marker tags.app/Providers/AppServiceProvider for global sanitization.addAllowedAttributes(['xlink:href' => ['href']]) for SVG links.null, log, or reject with HTTP 400).$this->app->bind(DOMSanitizer::class, function ($app) {
return new DOMSanitizer(DOMSanitizer::SVG);
});
Sanitizer facade for concise usage:
use Facades\App\Sanitizer;
$cleanSVG = Sanitizer::sanitize($userUpload);
@sanitize directives for templates:
Blade::directive('sanitize', function ($expression) {
return "<?php echo app(Rhukster\DomSanitizer\DOMSanitizer::class)->sanitize({$expression}); ?>";
});
libxml: Required for DOM parsing. Ensure extension=php_libxml is enabled in php.ini.dom: Also required. Verify with php -m | grep dom.strip_tags) to replace.app/Services/SVGService.php to use DOMSanitizer.@sanitize).libxml_disable_entity_loader).strip_tags/preg_replace for XML/HTML/SVG.htmlspecialchars for non-DOM content.spatie/laravel-medialibrary for SVG uploads.composer require rhukster/dom-sanitizer:^1.0.11
config/sanitizer.php:
return [
'default_mode' => DOMSanitizer::SVG,
'options' => [
'remove-namespaces' => env('SANITIZER_REMOVE_NAMESPACES', true),
],
];
AppServiceProvider:
public function register() {
$this->app->singleton(DOMSanitizer::class, function ($app) {
return new DOMSanitizer(config('sanitizer.default_mode'), config('sanitizer.options'));
});
}
app/Http/Kernel.php:
protected $middleware = [
\App\Http\Middleware\SanitizeXML::class,
];
PHPUnit).public function testSVGSanitization() {
$sanitizer = $this->app->make(DOMSanitizer::class);
$maliciousSVG = '<svg><script>alert(1)</script></svg>';
$cleanSVG = $sanitizer->sanitize($maliciousSVG);
$this->assertNotContains('script', $cleanSVG);
}
How can I help you explore Laravel packages today?