Once untrusted data enters the system, it must be handled with care.
Validation shapes the data
— but escaping determines where that data is allowed to go.
Security is not just about rejecting bad input.
It’s about ensuring that even valid input cannot break out of its intended context.
This page introduces the mental model of contextual output encoding
— the quiet discipline that keeps untrusted data in its place.
Escaping is not a universal transformation.
It is a context‑specific contract.
The same string must be escaped differently
depending on where it is placed:
There is no “one escape to rule them all.”
Security comes from choosing the right encoding for the right context.
When outputting untrusted data into HTML,
the safe default is to
escape:
< > & " '
This prevents:
Most template engines do this automatically.
Security comes from not disabling it.
HTML attributes are a different context
with different risks.
Example:
<input value="<?= $escaped ?>">
Here, escaping must prevent:
Attribute escaping is stricter than HTML escaping.
Treat it as a separate boundary.
Never place untrusted data directly into JavaScript.
If you must, use:
Example:
<script>
const data = <?= json_encode($safeData, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT) ?>;
</script>
This prevents:
JavaScript is the most fragile boundary.
Treat it with respect.
URLs are another context entirely.
Example:
<a href="/search?q=<?= urlencode($query) ?>">
URL encoding prevents:
Never concatenate untrusted data into URLs without encoding.
SQL is not escaped — it is parameterized.
Example: code php> $stmt = $pdo→prepare('SELECT * FROM users WHERE email = ?'); $stmt→execute([$email]); </code> Parameterization prevents:
Escaping SQL manually is fragile and error‑prone.
Use parameters. Always.
Shell commands are extremely dangerous.
If you must use them:
The safest shell command is the one you never run.
Most modern template engines:
Trust the defaults.
Avoid the escape hatches.
Validation shapes the data.
Escaping keeps it in its lane.
You need both:
Security is layered, not singular.
Escaping and output encoding are about context, not characters.
A secure system:
Security is not about distrusting the data
—it’s about respecting the boundaries.
This page describes secure defaults and common practices in modern PHP. It is not a complete security guide, and it does not replace formal audits or framework‑specific documentation. These principles are consistent enough to be useful, but security always requires context, judgment, and ongoing review.