Use HTML Purifier to prevent XSS attack in PHP

Tram Ho

I. Introduction

How did I mention the XSS error that my site was hacked by? Specifically, I was attacked by hacker by Stored XSS error. I would like to explain more specifically about this XSS error.

Stored XSS: a form of attack that hackers directly insert malicious code into the database of the website. This type of attack occurs when the data that is sent to the server is not thoroughly tested but stored directly into the database. When users access this site, malicious scripts will be executed in conjunction with the process of loading the website.

In PHP, there is a function called strip_tags , which removes html characters from a string.

For example you have a string containing html tags, now you need to remove it from this string. You can do the following:

And we get the desired result:

<p>Test paragraph.</p> <a href="#fragment">Other text</a>

Although strip_tags can remove html characters for our data, it only deletes certain tags. Each time you call the function, you must specify the tag you want to delete. So the solution here is to use the HTML Purifier.

II. main content

Install the HTML Purifier package

HTML Purifier is available in packagist.org . If you are using composer to manage dependencies. To install the package, execute the following command:

After successfully installing the package will be added in composer.json.

Use the HTML Purifier package

Create File App Support HTMLPurifier.php to setup config for HTMLPurifier

With HTMLPurifier you do not need to fill the list of html tags anymore, instead we whitelist the attributes only such as class, url, … very convenient, right?

And at the store data we want to use just call it out

With HTMLPurifier the unnecessary html tags have been removed and XSS attacks are somewhat prevented.

Demo

III. Conclusion

HTML Purifier is an effective packge for XSS prevention solutions. Protect your site to the best, providing the most effective user experience. This is just one of many packages in countless solutions to prevent and prevent XSS. Look forward to the suggestions from everyone.

Share the news now

Source : Viblo