I usually do this:
echo json_encode($result);
But I see that people sometimes do this:
echo htmlspecialchars( json_encode($result), ENT_NOQUOTES );
Why would you use htmlspecialchars on JSON?
I don't know php, so i'll assume htmlspecialchars escapes any html special characters.
Given that assumption then the use case is planting json data directly inside html content, a la
echo "<script>"
echo json_encode($result)
echo "</script>"
Given json encoding only encodes content to avoid escaping from the JS parser, this scenario would allow someone to insert JSON data that the html parser interpreted as ending the script tag.
Something like
{"foo": "</script><script>doSomethingEvil()</script>"}
would then reach the browser as
<script>{"foo": "</script><script>doSomethingEvil()</script>"}<script>
Which clearly results in doSomethingEvil() being executed. By escaping any html tokens you end up sending something like
<script>{"foo": "</script><script>doSomethingEvil()</script>"}<script>
Instead, which avoids the XSS vulnerability.
A far better solution to this problem is to simply not send JSON data directly in an HTML source (JSON encoding just makes the content safe to embed in JS, not HTML)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With