Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

andyunleash's avatar

Cleaning HTML input?

Hi all,

I'm getting deeper into Laravel and I'm just working out how best to work with user Entered HTML.

For example, I'm offering a WYSIWYG (in this case Redactor) to user so they can add tags to their content - the usual suspects like image links, h tags, ul, ol etc

However obviously I don't want them to be able to insert script tags, style tags etc and just have the basics.

Is there something within the Laravel core or a good package that can be used for this purpose? I.E allowing HTML to be stored and output safely?

Traditionally when just building PHP stuff before Laravel I've used HTMLPurify and I'm aware there is a package floating around for it for Laravel, but I wanted to see if I'm missing something simple within the core itself?

Many thanks!

0 likes
9 replies
andyunleash's avatar

It's a good read but it doesn't really answer my question. I need to be able to output some safe HTML but no everything and not nothing.

andyunleash's avatar

Thanks both! For HTML tidy I couldn't see there if it makes it possible to remove certain tags, like script for example?

Swaz's avatar

You could do something like this in the model.

It uses the strip_tags function, the second parameter is for allowable tags. https://php.net/strip_tags

class Post extends Model {

    public function setContentAttribute($input) 
    {   
        $this->attributes['content'] = strip_tags($input, '<h1><h2><h3><p><span><ol><ul><li>');
    }
}
1 like
andyunleash's avatar

@Swaz strip_tags unfortunately isn't perfect as it does allow certain attributes through on allowed tags, for example, javascript hover events. Also it can be a bit heavy handed and break the HTML.

It does sound like my original mention of HTMLPurifier is going to be the best choice moving forward, thanks all for your input though!

Please or to participate in this conversation.