Skip to content
← Back to Snippets
Code

Sanitize HTML Output

Escapes browser-facing text with `htmlspecialchars()` at render time so names, notes, and labels cannot become executable HTML.

Purpose

Escapes browser-facing text with `htmlspecialchars()` at render time so names, notes, and labels cannot become executable HTML.

Snippet details

ContextSecurityLevelProductionCopy-and-paste statusMarked safe after review.

Categories

  • Security

Code

<?php

/*
 * Copyright (c) 2026 Jeffery L. Paris <jparis@phpog.com>.
 * Free for personal and internal use. Paid project use requires visible credit
 * to Jeffery L. Paris. Corporate use requires a paid license fee unless a
 * separate written license states otherwise.
 */

/**
 * Sanitize HTML Output.
 *
 * Purpose:
 * Escapes text values at the browser-rendering boundary with
 * `htmlspecialchars()` so untrusted text is displayed instead of executed.
 *
 * @param array $raw_values Labels and text values that will be rendered in HTML.
 * @return array HTML-safe values using the same keys.
 */
function ogSnippetSanitizeHtmlOutput(array $raw_values): array {
	$escaped_values = array();

	foreach ($raw_values as $field_name => $field_value) {
		if (is_scalar($field_value) === false) {
			$escaped_values[$field_name] = '';
			continue;
		}

		$escaped_values[$field_name] = htmlspecialchars((string) $field_value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
	}

	return $escaped_values;
}

$weyland_yutani_report = array(
	'crew_member' => 'Ripley <Lt.>',
	'incident_note' => '<script>alert("xenomorph")</script> contained in lab text'
);

$safe_report = ogSnippetSanitizeHtmlOutput($weyland_yutani_report);

echo '<p>'.$safe_report['crew_member'].'</p>';
echo '<p>'.$safe_report['incident_note'].'</p>';