php · level 3 · unit 5 · lesson 2
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
Escaped when saved, and again when shown. What appears?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
<?php
function e(string $text): string {
return htmlspecialchars($text, ENT_QUOTES);
}
$_POST["title"] = "Tom & Jerry";
$saved = e($_POST["title"]);
echo "<h1>" . e($saved) . "</h1>\n";
your turn
Your turn. Keep the guestbook safe.
Pass ENT_QUOTES in the first blank. Type an attack as the second message, like a script tag. Then escape the message in the last blank too.
fix it
A search link breaks out of its box. Fix it.
- Read the output. The quote after cats closes the
valueattribute, andonmouseoverbecomes a real attribute of the box. - The helper is written, but the search text never goes through it.
- On line 6, wrap
$_GET["q"]ine( ), then run it.
nailed it
your pages show code instead of running it. :D
- Escape once, at the moment a value goes into HTML.
- Use
ENT_QUOTESso quotes inside HTML attributes are escaped. - Escaping twice shows visitors codes like
&amp;.
new words in your collection
- HTML attribute
- double escaping
This lesson isn’t saved. A free account remembers every lesson you finish.