PHP preventing XSS with htmlspecialchars
Cross-site scripting (XSS) happens when user-controlled text is put into a page as HTML. If a visitor submits a comment containing a script tag, and the page prints it as it is, the script runs in other visitors' browsers. The defence is to encode output for the place where it is inserted. For HTML text and attribute values, htmlspecialchars converts &, <, >, and quotes into entities so the browser shows them as text.
PHP
<?php
function e(string $text): string
{
return htmlspecialchars($text, ENT_QUOTES | ENT_SUBSTITUTE, "UTF-8");
}
$comment = '<script>alert("x")</script>';
echo "<p>" . $comment . "</p>", "\n";
echo "<p>" . e($comment) . "</p>", "\n";
$name = "O'Brien & \"Sons\"";
echo '<input value="' . e($name) . '">', "\n";
echo "q=" . urlencode("a b&c=d"), "\n";
echo json_encode(["note" => "</script>"], JSON_HEX_TAG), "\n";