How to secure HTML from a WYSIWYG editor in PHP
You secure HTML from a WYSIWYG editor on the server: before every save, you pass it through a sanitizer built on a parser and an allowlist of tags, attributes, classes and URLs. On top of that come supporting layers – displaying content in the right context, a Content Security Policy header, safe…
This post is also available in: Polski
You secure HTML from a WYSIWYG editor on the server: before every save, you pass it through a sanitizer built on a parser and an allowlist of tags, attributes, classes and URLs. On top of that come supporting layers – displaying content in the right context, a Content Security Policy header, safe uploads, a size limit and regression tests. The editor in the browser is a convenience for the editor, not a security boundary.
TL;DR
- The security boundary is the sanitizer on the server, called on every save – from the form, the API, imports and version restores.
- An HTML policy is an allowlist: element → attributes → value pattern → classes → CSS properties → URL schemes. A blocklist will always let something through.
- Check URLs (
href,src,srcset,poster) after decoding entities and removing control characters. - A sanitizer does not work in a vacuum: CSP, upload checks, a size limit and safe rendering limit the impact of a failure in any layer.
- VEditor has an
HtmlSanitizerin PHP with the same allowlist as the editor; valid content from the editor comes back byte for byte, and everything else is removed.
Threat model: who can inject code, and how?
In a CMS the most dangerous variant is stored XSS. A malicious fragment gets into the database and then runs in the browser of anyone who opens the page – a reader, another editor or an administrator with full permissions. The attacker does not have to be an outsider: a low-privilege account (e.g. “author” or “contributor”), a stolen password or an external system you import content from is enough.
Typical sources of untrusted HTML in an application with an editor:
| Source | Example | Does it go through the editor? |
|---|---|---|
| Form with the editor | saving an article | usually yes, but not necessarily |
| Direct HTTP request | curl, a modified form, JavaScript disabled | no |
| API and mobile app | REST/JSON endpoint | no |
| Import | migration from an old CMS, CSV, RSS | no |
| Pasting | content copied from someone else's page | yes, but the editor runs on the client side |
| AI | output of a language model | depends on the integration |
| Version restore | a revision saved before the rules changed | no |
The conclusion is simple: one place in the code that every content save passes through, with the sanitizer in it. We cover this in more detail, with examples of bypassing the editor, in the article Why filtering HTML in the browser is not enough.
Layer 1: the sanitizer on save
Why an allowlist?
A sanitizer can work in two ways: remove what is known to be dangerous (a blocklist), or keep only what is known to be needed (an allowlist). A blocklist loses to every new trick – a new event attribute, an unusual encoding or an element the filter's author did not think of. An allowlist rejects the unknown by default. You will find a comparison of both approaches, with an example of a filter bypassed in one line, in the article HTML allowlist or blocklist.
A good policy describes not only tag names, but also:
- which attributes a given element may have (e.g.
a–href,title,rel,target); - what format an attribute value has (e.g.
widthin pixels only,titlewithout quotes and angle brackets); - which CSS classes are allowed, and on which elements;
- which CSS properties are allowed in the
styleattribute, and with which values; - which URL schemes are allowed through.
A parser instead of regular expressions
HTML has to be parsed into a tree and filtered node by node, not searched for strings in the text. In PHP the natural choice is DOMDocument. The parser itself, however, secures nothing – it is just a tool for building the tree. How to design a sanitizer on top of it that walks the tree, unwraps unknown elements and serialises the result is described in the article A secure HTML sanitizer with PHP DOMDocument.
URLs after normalisation
The most common mistake in home-grown filters is checking the URL “as it arrived”. Before interpreting a URL, the browser decodes entities and ignores tabs and newlines, so both links below lead to javascript::
<a href="jav	ascript:alert(1)">View</a>
<a href="javascript:alert(1)">View</a>
The sanitizer must check the scheme only after decoding entities (the parser does this) and after removing control characters. A safe set for editorial content is http, https, mailto, tel and relative URLs. The same applies to every entry in srcset – an attribute with several URLs is easy to overlook.
Layer 2: attributes, identifiers and links
Even without scripts, HTML can harm the page it is displayed on:
- Event attributes (
onerror,onload,onmouseover…) – have no place in editorial content; the allowlist simply does not know them. - Identifiers – an element with
id="config"can overwrite a global variable used by the page's script. This is DOM clobbering, described in detail in the article DOM clobbering – how to protect your application from identifier collisions. - Links opening in a new tab –
target="_blank"withoutrel="noopener noreferrer"gives the opened page access towindow.opener. - Styles – an arbitrary
stylelets someone, for example, cover the page with a fake login form; allow only specific properties and values.
Layer 3: embeds and media
An iframe in the content is a window onto someone else's page. A sensible policy allows only specific hosts (e.g. the YouTube and Vimeo players), only in a defined container and with enforced sandbox and referrerpolicy attributes. Elements such as object, embed, form, meta or base have no justification in an article's content. The details – the host list, building the URL on the server, the sandbox and allow attributes – are described in the article Safely embedding YouTube and Vimeo in a CMS.
Layer 4: size and encoding
A sanitizer that parses arbitrarily large input is an easy target for a denial-of-service attack. Set a size limit checked before parsing, clean up invalid UTF-8 and make sure that processing time grows linearly even for deeply nested documents. We discuss measurements and how to set limits in the article HTML sanitizer performance – size limits.
Layer 5: displaying in the right context
Sanitised HTML is safe as an HTML fragment in the body of the page – and only there. The same string inserted into a different context needs different treatment:
| Context | What to do |
|---|---|
Page content (<div>) | insert the sanitised HTML without escaping |
A <textarea> field in the edit form | htmlspecialchars() – otherwise </textarea> in the content will close the field |
An HTML attribute (e.g. data-preview) | htmlspecialchars() with ENT_QUOTES |
A script (<script>) | json_encode() with the JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS, JSON_HEX_QUOT flags |
| Title, meta description, plain-text email | extract the text only, do not insert HTML |
A separate trap is processing HTML after sanitisation: a template filter, Markdown conversion, html_entity_decode() or re-parsing with a different parser. Any such transformation can change the meaning of the sanitised code. The most insidious version of this problem is mutation XSS – we describe it in the article Mutation XSS (mXSS) – how HTML parsing can change the security of content.
Layer 6: Content Security Policy
CSP does not clean content, but it limits the damage when something slips through: an injected <script> without the correct nonce will not run, and frames outside the list will not load. The policy for a page with an editor must account for a nonce for the editor's script, allowed styles in attributes, player frames and upload previews. You will find a ready-made configuration, with each directive explained, in the article Content Security Policy (CSP) and a WYSIWYG editor.
Layer 7: file uploads
Image upload is a separate endpoint that accepts files from users – and a separate attack surface: PHP files posing as images, SVG with a script, huge files. Check the type and size, re-encode images and store them outside directories where PHP is executed. We describe the full architecture in the article Secure image uploads in a CMS editor.
Example: saving and displaying in plain PHP
The code below comes from the VEditor documentation (integration with PHP without a framework). The order matters: CSRF first, then sanitisation with handling of the size limit, and saving last.
<?php
// save.php
require __DIR__ . '/vendor/autoload.php';
use VEditor\HtmlSanitizer;
session_start();
$styles = []; // the same array as the editor's `styles` option
if (!hash_equals($_SESSION['csrf_token'] ?? '', (string) ($_POST['csrf'] ?? ''))) {
http_response_code(403);
exit;
}
try {
$clean = (new HtmlSanitizer())->allowStyles($styles)->sanitize((string) $_POST['content']);
} catch (LengthException $e) {
http_response_code(413);
exit('The content is too large.');
}
// save $clean
Before this code, your application should also check that the user is logged in and is allowed to edit the record – a sanitizer does not replace authorisation. Displaying:
<link rel="stylesheet" href="/veditor/veditor-content.css">
<div class="veditor-content"><?= $article['body'] ?></div>
You output the content here without escaping only because it went through the sanitizer on save. If the database contains older entries saved without sanitisation, first pass them through the sanitizer with a one-off script – on a copy of the database, with a change report.
How to test the protection
Sanitizer tests have two halves, and both are equally important:
- Negative tests – malicious payloads sent directly to the sanitizer or the endpoint, bypassing the editor. You will find a catalogue of typical vectors in the article XSS in WYSIWYG editors – common attack vectors.
- Positive tests – real documents with headings, lists, tables, images and embedded videos. A sanitizer that “safely” destroys tables will end up switched off by a frustrated team.
An example PHPUnit test for both cases:
use PHPUnit\Framework\TestCase;
use VEditor\HtmlSanitizer;
final class ArticleSanitizerTest extends TestCase
{
public function testRemovesEventHandlers(): void
{
$clean = (new HtmlSanitizer())->sanitize('<p>Text</p><img src="/a.jpg" alt="" onerror="alert(1)">');
$this->assertStringNotContainsString('onerror', $clean);
}
public function testKeepsValidContentUnchanged(): void
{
$html = '<h2>Subheading</h2><p>A paragraph with <strong>bold text</strong>.</p>';
$this->assertSame($html, (new HtmlSanitizer())->sanitize($html));
}
}
The second test works as a regression test: if after an update someone changes the rules and valid content starts to change, you will find out before deployment. It is worth feeding it with real editor.getContent() output from your CMS.
Deployment checklist
- Every content save (form, API, import, version restore) goes through the sanitizer on the server.
- Authorisation and CSRF are checked before sanitisation.
- The policy is an allowlist of elements, attributes, value patterns, classes, styles and URL schemes.
- URLs are checked after normalisation, including every
srcsetentry. - Identifiers in the content have a prefix that does not collide with the page's code.
iframeonly from the host list, withsandbox; noobject,embed,form,base,meta.- The size limit is checked before parsing; exceeding it produces a clear error (e.g. HTTP 413).
- Content is displayed in a container; escaped in
<textarea>, attributes and scripts. - The page sends a CSP with a nonce for scripts.
- Upload checks the type and size, re-encodes images and stores them outside executable directories.
- Negative and positive tests run on every update of the editor, PHP and the rules.
How it works in VEditor
VEditor splits responsibility as described above: the editor cleans content for the editor's convenience, and the security boundary is VEditor\HtmlSanitizer on the server. The sanitizer is built on PHP's DOMDocument, with no libraries, and uses the same allowlist of tags, attributes, classes and CSS properties as the editor's schema in JavaScript. As a result, valid content generated by the editor comes back byte for byte, and everything the editor would not have generated disappears: unknown elements keep their text, disallowed attributes are removed, and dangerous elements (script, style, object, form…) disappear together with their content.
According to the documentation, the sanitizer:
- lets through only URLs with the
http,https,mailtoandtelschemes and relative URLs, after removing control characters, and checks everysrcsetentry; - allows identifiers only with the
ve-prefix; - adds
rel="noopener noreferrer"to links withtarget="_blank"; - keeps
iframeonly as a YouTube (no-cookie) or Vimeo video insidefigure, with enforcedsandboxandreferrerpolicy; - throws
LengthExceptionabovemaxLength(1 MB by default) and cleans up invalid UTF-8 before parsing.
In the published tests, typical XSS payloads sent straight to HtmlSanitizer::sanitize() – including <script>, <svg onload>, <img onerror>, encoded javascript: links, data:text/html;base64 links, mXSS via <noscript>, foreign <iframe>, <object>, <base href> and id="cookie" – did not survive sanitisation. This is the result for a specific set of samples, not a promise of resistance to every future technique. The integrations for Laravel, Symfony and Yii2 provide a sanitize() method and pass the CSP nonce to the editor's script; VEditor has no npm or Composer dependencies. What remains on your side: authorisation, CSRF, the CSP header, safe uploads and displaying content in the right context.
FAQ
Isn't htmlspecialchars() enough?
It is enough if you want to show HTML as text. In rich text content it will destroy the formatting – instead of bold text, the reader will see <strong>. Allowed HTML needs a sanitizer, and htmlspecialchars() stays for text fields, attributes and <textarea>.
Sanitise on save or on display?
On save, because then the database contains only safe data, and displaying does not cost a parse on every page view. After changing the sanitizer rules, pass existing entries through the new version as part of a migration.
What about content saved before the sanitizer was introduced?
Make a copy of the database, pass all records through the sanitizer and compare the result with the original. Review the records that changed by hand – usually it is old formatting, sometimes the trace of an attack.
Does CSP replace the sanitizer?
No. CSP restricts script execution and resource loading, but it will not remove, for example, a fake form built from allowed elements or a phishing link. It is the second layer, not the first.
What does sanitisation cost in terms of performance?
That depends on the document size and the algorithm. The key things are a size limit and the absence of loops with quadratic complexity. For reference: VEditor's published measurements (PHP 8.2 on a developer laptop) give 425 ms for 12,000 formatted paragraphs (996 KB) and 1 ms for 10,000 nested blockquotes.
Try VEditor in practice
If you are building a CMS in PHP, start with the sanitizer documentation and the description of how responsibility is split between the editor and your application. In the demo you can paste your own documents and see what HTML reaches the server.