php · level 2 · unit 4 · lesson 4
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
a visitor's text before you show it on a page.
Web pages are written in . Tags in angle brackets, like <b> for bold, tell the browser what to do. If a visitor types a tag into your form and you echo it onto a page, the browser obeys it.
With a <script> tag, a stranger could run their own code on everyone's screen. That attack is called . The cure is to escape the text: swap each special character for a safe code, like < for <, so the browser shows it instead of obeying it.
escapes for you. Store what the visitor typed as it is, and escape it every time you show it.
<?php
$_POST = ["comment" => "<b>Great</b> cakes & tea"];
$comment = $_POST["comment"];
echo htmlspecialchars($comment) . "\n";
echo htmlspecialchars('Zoe said "wow"') . "\n"; Gwecode shows your output as plain text, so you see the safe codes themselves, the way a browser receives them.
guess first
A maths fan leaves a review. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
<?php
$review = "5 < 6 & tasty";
echo htmlspecialchars($review) . "\n";
your turn
Your turn. Try to sneak in some HTML.
Type a nickname with some HTML in it, like <b>Ace</b>. Run it and compare the two lines.
fix it
This message would run on every screen. Make it safe.
- The visitor's text goes onto the page exactly as typed, tags and all.
- Escape it on the way out, at the moment you echo it.
- Change line 4 to
echo "New message: " . htmlspecialchars($message) . "\n";, then press run.
nailed it
visitors cannot hijack your pages now. :D
- A browser obeys any HTML tags you echo.
htmlspecialcharsescapes text so it is shown, not obeyed.- Store text as typed, and escape it when you show it.
new words in your collection
- HTML
- cross-site scripting
- escape
- htmlspecialchars
This lesson isn’t saved. A free account remembers every lesson you finish.