Do I need to escape text/plain or text/javascript?

Go To


Suppose I have something like this:

if ($command === 'txt') {
    header('Content-type: text/plain;charset=utf-8');
    echo $result;
} else ($command === 'js') {
    $json = array( $result );
    header('Content-type: text/javascript;charset=utf-8');
    echo $callback . '(' . substr(json_encode($json), 1, -1) . ');';

Can I use htmlspecialchars on the echo statements, it messes it up if it's interpret as html, on the other hand does not having them leave the risk that someone may try doing an xss attack if the browser does interpret it as html.

What should I do? Should I not worry and not htmlspecialchars?

2012-04-03 20:04
by qwertymk
Anyone that uses so kwality a browser that it interprets plain text as HTML has no excuse - Ignacio Vazquez-Abrams 2012-04-03 20:10


No, you should not use htmlspecialchars. Neither of those would make sense, since htmlspecialchars is intended to avoid HTML injection. However, if you use JSON, your client code needs to take care how it uses the returned value.

For instance, injecting it into innerHTML would not be safe.

2012-04-03 20:06
by Matthew Flaschen