Skip to content

CkSanitizer

Job: keep the markup an editor writes — formatting, links, images, video — and nothing else, written anew so that a browser builds exactly the tree the library judged.

A description, a comment, a biography typed in a rich-text editor arrives as HTML, and it is HTML you want to store: the bold, the lists, the links are the content. But markup from outside is also the classic way script gets into a page. CkSanitizer::Html reads the value with a real HTML5 parser — the grammar a browser uses, the same tree for the same text — walks the tree it gets, keeps the elements and attributes on its allow-list, reads every address through CkWeb::Url or CkEmail::Address, and writes the result from the tree element by element, every text and every attribute value encoded. Nothing in the result can open a tag it did not write, and reading the result again changes nothing. What stays is chosen by an HtmlPolicy: formatting alone, or formatting and media. There is no third policy and no switch that lets a style, a script or a frame through.

The result is for the body of a page — a <div> your template fills. It is never safe inside an attribute, a script or a style, where no markup is. For a value that should carry no markup at all, CkText::Html is the other answer: the plain text out of it.

A value that cannot be used answers '' — nothing throws unless you ask (see How it works). A value that is not text — a number, an array — is refused as "not markup" rather than written out as text.

Quick look

use SafeCoder\CommonKit\CkSanitizer;
use SafeCoder\CommonKit\Enums\HtmlPolicy;

CkSanitizer::Html('<p>Hello <b>world</b></p>');                          // -> '<p>Hello <b>world</b></p>'
CkSanitizer::Html('<p onclick="alert(1)">Hi<script>x()</script></p>');   // -> '<p>Hi</p>'
CkSanitizer::Html('<a href="javascript:alert(1)">click</a>');            // -> '<a>click</a>'
CkSanitizer::Html('<img src="/php/classes/cksanitizer/x" onerror="alert(1)">');                   // -> '<img src="/php/classes/cksanitizer/x">'
CkSanitizer::Html('<a href="HTTPS://EXAMPLE.COM/a" target="_blank">x</a>');   // -> '<a href="https://example.com/a" target="_blank" rel="noopener noreferrer">x</a>'
CkSanitizer::Html('<script>alert(1)</script>');                          // -> ''   (nothing left — rejected)
CkSanitizer::Html(
    input: '<p>a<img src="/a.png">b</p>',
    policy: HtmlPolicy::Formatting
);                                                                       // -> '<p>ab</p>'
CkSanitizer::Explain('<p></p>');                                         // -> 'nothing left once the markup is cleaned'

Methods

Html

The markup, kept safe.

static function Html(
    mixed $input = null,
    HtmlPolicy $policy = CkSettings::DefaultHtmlPolicy,
    int $maxLength = CkSettings::MaxTextInputLength,
    bool $truncate = true,
    mixed $fallback = null,
    bool $throwIfInvalid = CkSettings::DefaultThrowIfInvalid
): string
Parameter Type Default What it does
input mixed null The raw markup, or plain text: text, or an object that writes itself as text. Anything else is refused.
policy HtmlPolicy CkSettings::DefaultHtmlPolicy (Media) What to keep: Media keeps formatting, links, images, video and audio; Formatting removes the media with what it holds.
maxLength int CkSettings::MaxTextInputLength (50,000) Maximum length of the markup written, in characters. Values below 1 fall back to the default.
truncate bool true Cut over-long markup to fit (the default) instead of rejecting it. The cut keeps every element closed and never splits a character or an entity.
fallback mixed null Backup value used when the result would be empty. It goes through the same cleaning and checks as input, with the same options; a fallback that is itself rejected answers ''.
throwIfInvalid bool CkSettings::DefaultThrowIfInvalid (false) Pass true to throw a CkSanitizerException that says why, instead of answering '', when neither the value nor the fallback can be used.

Returns

When Default With throwIfInvalid: true
The value (or the fallback) holds markup with something to show The markup, written anew: '<p>Hello <b>world</b></p>' The markup, written anew: '<p>Hello <b>world</b></p>'
Rejected: missing, not text, over 100,000 characters (CkSettings::MaxRichTextInputLength), nothing left once the markup is cleaned — no text and no image, video or audio — or over maxLength with truncate off Empty string Throws CkSanitizerException — carries Input, Expected and Reason

For the body of a page, never for an attribute, a script or a style.

What stays. Under Formatting: p, br, hr, div, span, h1 to h6, b, strong, i, em, u, s, del, ins, sub, sup, ul, ol, li, dl, dt, dd, blockquote, pre, code, kbd, mark, small, q, cite, abbr, figure, figcaption, the table elements (table, caption, colgroup, col, thead, tbody, tfoot, tr, th, td — inside a table; anywhere else a browser drops the tags and keeps the text, and so does the library), and a. Under Media, the default, img, video, audio and source as well. Per element, only the attributes that carry content:

Element Attributes kept
a href, title; target only as _blank, and then rel="noopener noreferrer" is written beside it
abbr title
img src, alt, title, width, height
video src, poster, controls, width, height
audio src, controls
source src, type — a video/* or audio/* type; inside video or audio only
ol start
td, th colspan, rowspan

A width, height, colspan, rowspan or start is a count, written as the number it reads as; style, class, id, srcset and every on… handler are dropped everywhere.

Addresses. href, src and poster are read the way a browser reads them — a tab or a line break inside dropped first, spaces at the ends trimmed — then judged by their scheme: http and https go through CkWeb::Url and come back normalized; mailto: on a link goes through CkEmail::Address, the address alone; javascript:, data:, vbscript:, file: and every other scheme is refused. A value with no scheme is a #fragment or a path relative to the page, kept as written — unless it begins with two slashes (//evil.example, a backslash counting as a slash), which names another host. A link whose address is refused keeps its text and loses the attribute; an image or a source with no usable address is removed, and so is a video or audio element with no usable address of its own and no usable source inside it.

What goes. script, style, iframe, object, embed, applet, svg, math, form, noscript, template, textarea, title, head, frameset and the other elements that hold code, raw text or foreign content go with everything inside them; so does a comment, a doctype and a processing instruction. Any other element — font, section, center, button — is unwrapped: its text and what it holds stay in its place, the tag goes. An element nested deeper than 64 kept elements (CkSettings::MaxRichTextDepth) is unwrapped too.

How it is written. From the tree, element by element: tag names in lower case, attributes in one fixed order, text with <, >, & and the no-break space encoded, an attribute value with " as well, so no value can open a tag or close the quotes around it. Before the markup is handed out it is read once more, and handed out only when the second reading writes the same text — so what Html answers, it answers again unchanged, which is what a value saved and read back relies on.

use SafeCoder\CommonKit\CkSanitizer;

CkSanitizer::Html('<P class="x">Upper<B>case</B></P>');          // -> '<p>Upper<b>case</b></p>'   (tag names lower-cased, the attribute gone)
CkSanitizer::Html('<p>Save &amp; close</p>');                    // -> '<p>Save &amp; close</p>'
CkSanitizer::Html('<p>5 &lt; 6</p>');                            // -> '<p>5 &lt; 6</p>'
CkSanitizer::Html('<b>unclosed');                                // -> '<b>unclosed</b>'   (every element written is closed)
CkSanitizer::Html('<p>one<p>two');                               // -> '<p>one</p><p>two</p>'
CkSanitizer::Html('<font color="red">old</font>');               // -> 'old'   (an element the policy does not name is unwrapped)
CkSanitizer::Html('<p>a<iframe src="https://x.example/"></iframe>b</p>');   // -> '<p>ab</p>'   (an embedding goes whole)
CkSanitizer::Html('<a href="mailto:Mary@Example.com">m</a>');     // -> '<a href="mailto:mary@example.com">m</a>'
CkSanitizer::Html('<a href="//evil.example/x">x</a>');            // -> '<a>x</a>'   (two slashes name another host)
CkSanitizer::Html('<video controls><source src="/v.mp4" type="video/mp4"></video>');   // -> '<video controls><source src="/v.mp4" type="video/mp4"></video>'
CkSanitizer::Html('<p>&nbsp;</p>');                              // -> ''   (an editor's empty paragraph: nothing left)

Truncation. maxLength counts the markup written, tags included — the number to size a column from. With truncate on, the cut is made at the tree: a text is shortened, an element that cannot fit together with its end tag is left out, and every element written is still closed, so the markup stays well-formed and within the limit. With truncate off, markup over the limit is rejected.

use SafeCoder\CommonKit\CkSanitizer;

CkSanitizer::Html(
    input: '<p>Hello world</p>',
    maxLength: 12
);   // -> '<p>Hello</p>'   (the text is cut, the paragraph still closed)
CkSanitizer::Html(
    input: '<p>Hello <b>big</b> world</p>',
    maxLength: 15
);   // -> '<p>Hello </p>'   (the bold could not fit with its end tag)
CkSanitizer::Html(
    input: '<p>Hello world</p>',
    maxLength: 12,
    truncate: false
);   // -> ''   (over the limit, and you asked not to cut)

Explain

Why not — in words, without an exception.

static function Explain(
    mixed $input = null,
    HtmlPolicy $policy = CkSettings::DefaultHtmlPolicy,
    int $maxLength = CkSettings::MaxTextInputLength,
    bool $truncate = true
): string
Parameter Type Default What it does
input mixed null The raw markup.
policy HtmlPolicy CkSettings::DefaultHtmlPolicy (Media) The policy Html would judge by.
maxLength int CkSettings::MaxTextInputLength (50,000) The limit Html would apply.
truncate bool true Whether Html would cut or refuse over-long markup.

Returns

When You get
Html would answer markup ''
It would not The reason, the same words the exception would carry — an answer, not a failure; it never throws

The form-friendly twin of throwIfInvalid: the message to show beside the field, without a try and catch. Every class with a reader has one, on the reader's own rules.

use SafeCoder\CommonKit\CkSanitizer;
use SafeCoder\CommonKit\Enums\HtmlPolicy;

CkSanitizer::Explain('<p>Hello</p>');                  // -> ''
CkSanitizer::Explain(null);                            // -> 'no value'
CkSanitizer::Explain('<script>alert(1)</script>');     // -> 'nothing left once the markup is cleaned'
CkSanitizer::Explain(
    input: '<img src="/a.png">',
    policy: HtmlPolicy::Formatting
);                                                     // -> 'nothing left once the markup is cleaned'
CkSanitizer::Explain(
    input: '<p>Hello world</p>',
    maxLength: 12,
    truncate: false
);                                                     // -> 'over 12 characters'
CkSanitizer::Explain(42);                              // -> 'a Int32 is not markup'

Rich text from a request

Every text reader of CkRequest and CkDictionary removes markup on the way in — String strips it and tidies the text, Html extracts the plain text — because for almost every field that is right. For the one field written in an editor, take the value from the bag as it is and hand it to Html here:

use SafeCoder\CommonKit\CkDictionary;
use SafeCoder\CommonKit\CkRequest;
use SafeCoder\CommonKit\CkSanitizer;

$_SERVER['REQUEST_METHOD'] = 'POST';
$_SERVER['CONTENT_TYPE'] = 'multipart/form-data';
$_POST = ['bio' => '<p>Hello <b>world</b><script>x()</script></p>'];

CkSanitizer::Html(CkDictionary::Value(CkRequest::Bag()->Body(), 'bio'));   // -> '<p>Hello <b>world</b></p>'
CkRequest::Html('bio');                                                    // -> 'Hello world'   (the plain text, for a field that should carry no markup)

The value stored is what Html wrote; the page that shows it places it in the body as it is, with no encoding — encoding it would show the tags as text — which is why it must go nowhere else.

The fallback

Html takes a fallback — spare markup used when the input is rejected. The fallback goes through the exact same cleaning and checks, with the same policy and limit; a bad fallback answers '' too.

use SafeCoder\CommonKit\CkSanitizer;

CkSanitizer::Html(
    input: '<script>x</script>',
    fallback: '<p onclick="x()">No description yet.</p>'
);   // -> '<p>No description yet.</p>'

Good to know

  • For the body of a page, and nowhere else. The result is safe where a browser reads markup as the content of an element. Inside an attribute, a <script>, a <style> or a URL no markup is safe, and this method makes no promise there.
  • Two policies, no third. There is no parameter that admits another element, another attribute, a style or a class. If an editor needs more, the library's allow-list is the place to decide it, once, for every caller.
  • An address is judged by its shape, not its destination. An image or video source must read as an http or https address, a relative path or a fragment; whether the host exists, or is public, is not asked — the reader's browser fetches it, not your server. CkWeb::IsPublicHost is for an address your server will call.
  • Relative addresses are kept as written. /docs/intro, ?page=2, #top and ./a b.html pass through unchanged; a browser resolves them against the page.
  • Content means something to see. Markup with no text and no media once cleaned — <p></p>, <p>&nbsp;</p>, a lone <hr>, a comment — is rejected as "nothing left once the markup is cleaned", and so is a link with nothing to click.
  • The length is the markup's. maxLength counts the characters written, tags and entities included; <p>é</p> is eight. Size the column from it.
  • Reading it again changes nothing. Every answer is a fixed point: Html of the answer is the answer, under the same policy — the promise a value saved and read back relies on.
  • Not every parser agrees about broken markup. The library's parser and a browser build the same tree for the markup Html writes; for the markup it reads they may differ at the edges — a stray </p>, text inside a <table> — and the library takes its own reading. The answer is safe either way; what differs is where a stray piece of text lands.
  • A provider's player is an embed, not markup. Html removes every iframe, a YouTube or Vimeo player included. Read the link with CkMedia and place its Iframe() where the page wants it, beside the sanitized text. A file's element — the video, audio or img that CkMedia's Player() and Tag() write — the Media policy keeps, with its source.
  • Non-empty in, empty out means rejected. That is the standard CommonKit signal for the string methods — check for '' where it matters.

If you want errors instead

Pass throwIfInvalid: true and a value that cannot be used raises a CkSanitizerException (from SafeCoder\CommonKit\Exceptions) instead of answering ''. The exception carries the Input and a short Reason — "no value", "nothing left once the markup is cleaned" — flattened into a one-line message. Markup that merely had something removed is not an error: removing is the job.

use SafeCoder\CommonKit\CkSanitizer;

CkSanitizer::Html(
    input: '<script>alert(1)</script>',
    throwIfInvalid: true
);   // throws CkSanitizerException — the message says why