tags:

views:

524

answers:

5

Is it necessary to filter/escape unsafe variables in <title> or other tags in <head> to prevent XSS?

+10  A: 

Strictly speaking it is necessary to do htmlspecialchars() on absolutely everything you output to a web page from PHP.

If you come to a point where this produces a wrong result (i.e. HTML code is showing up in the browser because of double encoding) you have found a design flaw in your application.

XSS would not be a problem if people would stick to this simple rule.

Tomalak
+3  A: 

Yes. You should always use the htmlspecialchars function on values that may contain HTML special characters.

Gumbo
+4  A: 

As others have said, yes. For example, someone might enter this for a title:

</title><script>doEvilStuff()</script>

Which would probably do evil stuff.

EDIT: You might want to do this instead:

htmlspecialchars(strip_tags($title))

Because most (all? some?) browsers won't interpret tags in the title correctly - that is, they'll actually show up in the title rather than doing what you'd expect.

Jesse Rusak
No need to strip_tags, when you html-escape it afterwards.
troelskn
For security, you're right, but I know that some browsers (all browsers?) treat tags literally in titles. So, if you use a <b> tag, it will show up literally rather than bolding the text.
Jesse Rusak
That's why I asked the question. So far I've seen every browser treat tags literally in <title>
Imran
Right - you still need to escape them, though, because a </title> could appear and then nastiness afterwards.
Jesse Rusak
Of course. If you run it through htmlspecialchars, it would be treated literally, because <b> then becomes <b> ... That's not special to the <title> tag.
troelskn
A: 

I prefer htmlentities().

A: 

Tilte is 'htmlspecialchar()' but ... htmlspecialchars()?