waHtmlSanitizer

Safe HTML code processing

Contents...

This class allows you to process HTML code received from external sources to safely display it on a web page.

Methods

  • __construct

    Constructor.

  • sanitize

    Returns HTML with potentially dangerous tags removed.

  • toPlainText

    Returns text contents from the source HTML code.

public function __construct ($options = [])

Constructor.

Parameters

  • $options

    Additional parameters as an array with the following keys:

    • close_broken_tags: flag requiring to auto-close missing HTML tags when executing method sanitize.

Example

$html = <<<HTML
<style>alert('I’m a potentially dangerous JavaScript!');</style>
<!-- unclosed strong tag -->
<p><strong>Hello there ;)</p>
HTML;
    
(new waHtmlSanitizer([
    'close_broken_tags' => true,
]))->sanitize($html);

Result

<p><strong>Привет ;)</strong></p>

public function sanitize ($content)

Returns HTML with potentially dangerous tags removed to prevent XSS attacks.

Parameters

  • $content

    Source HTML code.

Example

$html = <<<HTML
<style>alert('I’m a potentially dangerous JavaScript!');</style>
<p>Hello there ;)</p>
HTML;

(new waHtmlSanitizer())->sanitize($html);

Result

<p>Hello there ;)</p>

public function toPlainText ($content)

Returns text contents from the source HTML code.

Parameters

  • $content

    Source HTML code.

Example

$html = <<<HTML
<style>alert('I’m a potentially dangerous JavaScript!');</style>
<p>Hello there ;)</p>
HTML;

(new waHtmlSanitizer())->toPlainText($html)

Result

Hello there ;)