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

Htmlawed Laravel Package

fossar/htmlawed

Fork of kesar/HTMLawed maintained by selfoss and wallabag. A single-file (~45KB) PHP HTML filter/sanitizer that secures and tidies user input, making it standards-compliant for HTML/XHTML/XML, with extensive customization options.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require fossar/htmlawed:^1.3.4
    

    Note: Updated to version 1.3.4 to leverage new features and fixes.

  2. First Use Case Sanitize user-generated HTML with improved tag handling:

    use Fossar\HtmlAwed\HtmlAwed;
    
    $html = '<details><summary>Note</summary><p>Content</p></details>';
    $sanitizer = new HtmlAwed();
    $cleanHtml = $sanitizer->sanitize($html);
    
    // Output: <details><summary>Note</summary><p>Content</p></details>
    

    Now supports <details> with flow content (e.g., <p>) by default.

  3. Where to Look First


Implementation Patterns

Common Workflows

  1. Basic Sanitization (Updated)

    $sanitizer = new HtmlAwed();
    $clean = $sanitizer->sanitize($dirtyHtml);
    
    • Now automatically neutralizes illegal self-closing tags (e.g., <img/><img>).
    • Supports <details> with nested flow content by default.
  2. Custom Rules (Enhanced) Extend or override allowed tags/attributes with new defaults:

    $sanitizer = new HtmlAwed();
    $sanitizer->allowTags(['details', 'summary']); // Explicitly allowed by default now
    $sanitizer->allowAttributes('details', ['open']); // Example: Allow `open` attribute
    
  3. Laravel Integration (Optimized) Create a macro with versioned dependency:

    // app/Providers/AppServiceProvider.php
    use Illuminate\Support\Str;
    
    public function boot()
    {
        Str::macro('sanitizeHtml', function ($html) {
            return app(HtmlAwed::class)->sanitize($html);
        });
    }
    

    Ensure fossar/htmlawed:^1.3.4 is specified in composer.json.

  4. Form Request Validation (Updated) Combine with Laravel’s validation to handle new tag rules:

    public function rules()
    {
        return [
            'content' => [
                'required',
                function ($attribute, $value, $fail) {
                    $sanitizer = new HtmlAwed();
                    if ($sanitizer->sanitize($value) !== $value) {
                        $fail('HTML contains invalid tags or self-closing syntax.');
                    }
                },
            ],
        ];
    }
    
  5. Middleware for API Responses (New Use Case) Sanitize HTML in API responses with <details> support:

    // app/Http/Middleware/SanitizeHtml.php
    public function handle($request, Closure $next)
    {
        $response = $next($request);
        if ($response->isJson() && $request->has('html_content')) {
            $response->setData([
                'content' => app(HtmlAwed::class)->sanitize($request->html_content),
            ]);
        }
        return $response;
    }
    

    Now safely processes <details> elements in responses.


Gotchas and Tips

Pitfalls

  1. Self-Closing Tag Issues (Fixed)

    • Old: <img src="x" /> might break sanitization.
    • New: Automatically converted to <img src="x"> (neutralized).
    • Fix: No action needed—handled by default.
  2. <details> Tag Quirks

    • New: Supports flow content (e.g., <p>, <div>) inside <details> by default.
    • Gotcha: If you deny <details>, nested tags like <p> will also be stripped.
    • Fix: Explicitly allow both:
      $sanitizer->allowTags(['details', 'summary', 'p']);
      
  3. Attribute Whitelisting (Still Critical)

    • Forgetting to allow attributes on new tags (e.g., open for <details>) breaks functionality.
    • Fix: Always pair allowTags() with allowAttributes():
      $sanitizer->allowAttributes('details', ['open']);
      
  4. CSS/JS Injections (Unchanged)

    • Reminder: The package still does not sanitize style or event handlers.
    • Fix: Use denyAttributes():
      $sanitizer->denyAttributes('*', ['style', 'onclick']);
      
  5. Laravel Blade Conflicts (Updated)

    • New: <details> and <summary> are now safe in Blade with sanitizeHtml():
      {!! Str::sanitizeHtml($userHtml) !!}
      
    • Gotcha: Avoid mixing {{ }} (auto-escapes) with raw HTML. Use {!! !!} for sanitized output.

Debugging Tips

  1. Inspect Updated Rules Dump allowed tags/attributes to verify new defaults:

    $sanitizer = new HtmlAwed();
    dump($sanitizer->getAllowedTags()); // Includes 'details', 'summary'
    dump($sanitizer->getAllowedAttributes());
    
  2. Test Edge Cases (Updated)

    • Test with:
      • Self-closing tags: <img/><img> (auto-fixed).
      • <details> nesting: <details><p>Text</p></details> (now allowed).
      • Malformed <details>: <details><summary>Missing closing</summary> (handled).
  3. Fallback for Strict Mode (Adjusted) If strict sanitization breaks layouts, relax rules for new tags:

    $sanitizer->allowTags(['div', 'span', 'p', 'details', 'summary']);
    $sanitizer->allowAttributes('details', ['open']);
    

Extension Points

  1. Custom Sanitizer Class (Updated) Extend HtmlAwed to override new defaults:

    class AppHtmlAwed extends HtmlAwed
    {
        public function __construct()
        {
            parent::__construct();
            $this->denyTags(['embed']); // Example: Block new tags explicitly
            $this->allowAttributes('details', ['open', 'class']); // Extend defaults
        }
    }
    
  2. Hook into Laravel Events (New Tag Support) Sanitize HTML with <details> in Eloquent models:

    // app/Models/Comment.php
    protected static function boot()
    {
        static::creating(function ($model) {
            $model->content = app(AppHtmlAwed::class)->sanitize($model->content);
        });
    }
    
  3. Cache Sanitizer Instances (Optimized) Register the updated version as a singleton:

    // app/Providers/AppServiceProvider.php
    public function register()
    {
        $this->app->singleton(HtmlAwed::class, function () {
            $sanitizer = new HtmlAwed();
            $sanitizer->allowTags(['p', 'a', 'img', 'details', 'summary']);
            return $sanitizer;
        });
    }
    

    Ensures all requests use the latest 1.3.4 rules.

  4. New: Handle Self-Closing Tags in Legacy Code If legacy code relies on self-closing syntax, preprocess HTML:

    $html = preg_replace('/<(\w+)\s*\/?>/', '<$1>', $dirtyHtml);
    $clean = app(HtmlAwed::class)->sanitize($html);
    
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.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor