×

php · level 3 · unit 5 · lesson 2

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

Escape once, at the last moment, wherever the value lands.

htmlspecialchars stops cross-site scripting, XSS for short, between tags. Values also land inside an , like alt='...'. There, a stray quote ends the attribute early, and the attacker adds one of their own, such as onmouseover, which runs script. Passing ENT_QUOTES guarantees both kinds of quote are escaped.

Escape late: store the original text, and escape at the moment you echo it. Escape early as well and you get , where & becomes & and visitors see codes. A tiny helper called e() makes the right habit quick.

<?php
function e(string $text): string {
    return htmlspecialchars($text, ENT_QUOTES);
}
$comment = "<script>steal()</script>";
$name = "Mia's mum";
echo "<p>" . e($comment) . "</p>\n";
echo "<img alt='" . e($name) . "'>\n";

Recent versions of PHP escape single quotes even without ENT_QUOTES, but older servers do not, so always say it.