Suppose I have something like this:
if ($command === 'txt') {
header('Content-type: text/plain;charset=utf-8');
echo $result;
exit();
} else ($command === 'js') {
$json = array( $result );
header('Content-type: text/javascript;charset=utf-8');
echo $callback . '(' . substr(json_encode($json), 1, -1) . ');';
exit();
}
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?
No, you should not use
htmlspecialchars. Neither of those would make sense, sincehtmlspecialcharsis 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
innerHTMLwould not be safe.