Example
<?php
$comment = $_POST['comment'] ?? '';
function escapeHtml(string $value): string
{
return htmlspecialchars(
$value,
ENT_QUOTES | ENT_SUBSTITUTE,
'UTF-8'
);
}
?>
<p><?= escapeHtml($comment) ?></p>
Explanation
Never insert untrusted text directly into HTML. htmlspecialchars() converts characters such as <, >, &, and quotes into HTML entities.
Important
HTML escaping is context-specific. JavaScript, CSS, URLs, and HTML attributes can require different handling. Prefer avoiding inline JavaScript and build URLs with appropriate URL-encoding functions.