PHP 7: Maintaining and Upgrading Legacy Apps · Security Hardening for PHP 7 Apps
Fixing XSS in Legacy Templates
Systematically escape output in PHP templates mixed with logic.
Legacy templates often echo $row['name'] directly. Introduce an e() helper using htmlspecialchars(..., ENT_QUOTES, 'UTF-8'), replace raw echoes systematically (search for <?= $ and echo $), and consider moving templates to Twig, which auto-escapes. Add a Content Security Policy to reduce impact while the migration proceeds.
<?php
function e($value): string
{
return htmlspecialchars((string) $value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}
?>
<!-- Before -->
<td><?php echo $row['comment']; ?></td>
<!-- After -->
<td><?= e($row['comment']) ?></td>
Common pitfalls
- Escaping only some fields because they 'can't contain HTML'.
- Double-escaping data that was escaped on input.
- Forgetting attribute contexts (
value="<?= $x ?>").
Key points
- One escaping helper, used everywhere
- Search for raw echoes systematically
- Twig auto-escapes; CSP limits damage
Further reading: OWASP XSS Prevention Cheat Sheet
Practice questions
Why is moving to Twig a good long-term XSS fix?
Answer
Twig escapes output by default, so developers must explicitly opt out (|raw), making unsafe output visible in code review.
What does ENT_QUOTES add to htmlspecialchars?
Answer
It also escapes single quotes (double quotes are escaped by default), making the output safe inside single- or double-quoted HTML attributes.
Open in the app to mark lessons complete, take notes and track your progress.