No traps in the ads

Exercise 5 of 7 in chapter 6 · 200 XP · 4 objectives checked by tests

Topics covered: XSShtmlspecialchars()Validationis_string

Léo has found a new game. In the title of an ad, he typed "><script>alert('Léo')</script> and left the contact empty. The form came back with its errors… and a “Léo” pop-up appeared: his text had become code, run by the browser. This is an XSS vulnerability (cross-site scripting). With a real script, Léo could make someone else's page do anything at all, just by sending them a booby-trapped link or form.

Your mission

  1. In templates/proposer-annonce.php, escape every typed value with htmlspecialchars(): the three fields, and the errors, which repeat the typed price.
  2. Léo has a second trick up his sleeve: by sending titre[]=x, he makes an array arrive instead of a string, and the page crashes. In public/index.php, accept only strings: a field that is not one counts as empty.

Reminder

Everything that comes from outside (a form, an address, a cookie) is untrusted input. You check it on the way in (is_string(), ctype_digit()), and you escape it on the way out, when you display it in HTML (htmlspecialchars()). You need both: validation knows nothing about HTML, and escaping has no idea what a price is.

To replace a value that is not suitable, the ternary operator saves you a full if: condition ? valueIfTrue : valueIfFalse. For example, is_string($valeur) ? trim($valeur) : '' gives the cleaned-up value if it is a string, and '' otherwise.