PHP

Lesson 03

Output escaping for XSS

Escape untrusted values when rendering HTML so user content cannot become markup or script.

Good Code

templates/profile.php
<?php declare(strict_types=1);

function e(string $value): string
{
    return htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}
?>

<h1><?= e($user['name']) ?></h1>
<p><?= e($user['bio']) ?></p>

Bad Code

templates/profile.php
<?php
?>

<h1><?= $user['name'] ?></h1>
<p><?= $_GET['bio'] ?></p>

Review Notes

What to review

Good Code

The good version uses a small escaping helper for text rendered into HTML, including quotes and invalid byte substitution.

Bad Code

The bad version outputs database and request values directly. If those values contain HTML, the template will treat them as markup.

Takeaways

  • Prepared statements protect SQL, but HTML output still needs context-aware escaping.