Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Svg Sanitize Laravel Package

enshrined/svg-sanitize

PHP SVG/XML sanitizer inspired by DOMPurify. Clean untrusted SVGs with a simple sanitize() call, optional custom tag/attribute whitelists, remote reference stripping to prevent leaks, issue reporting, and output minification. Returns clean XML or false on parse errors.

View on GitHub
Deep Wiki
Context7

Getting Started

Install via Composer with composer require enshrined/svg-sanitize. Start by sanitizing a raw SVG string: instantiate enshrined\svgSanitize\Sanitizer, call sanitize($svg), and handle the result. A false return means parsing failed—inspect issues with getXmlIssues(). Use the CLI scanner (php svg-scanner.php path/to/file.svg) for quick local validation during development. The demo is invaluable for visualizing what gets stripped (e.g., <script>, onload, xlink:href to external URLs).

Implementation Patterns

  • Middleware/Validator integration: Wrap sanitization in Laravel’s Rule::forbiddenExtensions() or custom Rule::_svgSanitize(). Sanitize before storage:
    $svgContent = $request->file('logo')->get();
    $sanitizer = new Sanitizer();
    $cleanSvg = $sanitizer->sanitize($svgContent);
    if ($cleanSvg === false) {
        // Log issues, reject upload
        logger()->warning('SVG sanitization failed', $sanitizer->getXmlIssues());
        return response()->json(['error' => 'Invalid SVG'], 422);
    }
    Storage::put('logos/safe-logo.svg', $cleanSvg);
    
  • Custom allowlist for domain needs: Implement TagInterface/AttributeInterface to permit <use> with href only when pointing to local IDs (e.g., reject xlink:href="https://..." while allowing xlink:href="#icon-arrow"):
    $sanitizer->setAllowedTags([SvgTags::class]); // Only <svg>, <path>, <g>, <use>, etc.
    $sanitizer->setAllowedAttrs([SvgAttrs::class]); // Filter xlink:href in CustomAttrs
    
  • Multi-tenant security: Enable removeRemoteReferences(true) to block external assets and prevent SSRF. Combine with minify(true) in production to reduce storage/bandwidth.
  • Error logging & audit trails: On sanitization failure, forward getXmlIssues() to Sentry or Slack for real-time alerts. Include SVG source context (e.g., user_id, upload path) in logs.

Gotchas and Tips

  • Namespace case sensitivity: Pre-0.22 SVGs with xlink:Href (uppercase) fail silently; 0.22+ normalizes case, but legacy uploads may still break—always log getXmlIssues() and test with edge-case SVGs (e.g., mixed-case attributes).
  • XML fragility: Malformed SVGs (unclosed tags, unescaped &) cause XML parsing to fail before sanitization—enable libxml_use_internal_errors(true) and capture libxml_get_errors() before sanitize() to get human-readable diagnostics.
  • Silent success ≠ safe rendering: Sanitization removes XSS vectors but doesn’t ensure the SVG renders visibly (e.g., malformed <rect width="0"/> is "clean" but invisible). Validate rendering separately in staging.
  • GPL-2.0 licensing risk: If your app is proprietary/commercial, confirm GPL compatibility with legal—derivative works must be open-sourced under GPL. Consider alternatives (e.g., DOMPurify JS client-side for non-PHP contexts).
  • Performance optimization: Reuse Sanitizer instances (e.g., bind as singleton in AppServiceProvider). Avoid calling sanitize() on non-SVG files—check MIME type first (finfo_file($file, FILEINFO_MIME_TYPE) === 'image/svg+xml').
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport