htmlspecialchars()
function
Converts special HTML characters to entities. Essential for preventing XSS when outputting user data.
Syntax
htmlspecialchars(string $string, int $flags = ENT_QUOTES|ENT_SUBSTITUTE): string
Example
php
<?php
$input = '<script>alert("XSS")</script>';
echo htmlspecialchars($input, ENT_QUOTES, 'UTF-8');
// <script>alert("XSS")</script>
function e(string $s): string {
return htmlspecialchars($s, ENT_QUOTES|ENT_HTML5, 'UTF-8');
}
Always escape user data before rendering in HTML.