The problem is not in the input per se, it's in how you output it. If you echo
it directly into an HTML page then you need to HTML-encode it; that's true of all strings you include in an HTML page, not just cookies. If you are as a habit outputting unescaped strings into HTML then you probably have much easier to exploit XSS bugs than this(*).
The way to handle variable text properly for output into HTML is to wrap every variable in htmlspecialchars()
at the point you echo it into HTML (not as an input handling step). Do not use strip_tags()
—it is not designed as a security measure and it fails in a variety of circumstances. If you need to accept limited user-input markup use an HTML purifier library.
(*: how exploitable an HTML-injection-from-cookie is depends largely on how that cookie gets set. If there is any way an attacker can persuade your application to set another user's cookie to a specific value, it'll be easily exploitable; otherwise, in order to exploit the HTML injection they would have to find a cookie-fixation bug. That could be a header-injection bug in your app, or it could be any vulnerable application in a ‘neighbour domain’—an application at a.example.com
can set a cookie that will be read by an application at b.example.com
.)