I have seen multiple posts/examples where json_encode()
is used within htmlspecialchars()
to prevent XSS when using PHP in JavaScript embedded in HTML. Still, I have also seen examples where only json_encode()
is seen to be sufficient. For example:
// already sufficient?
<script type="application/json">
<? echo json_encode($value, JSON_HEX_QUOT|JSON_HEX_TAG|JSON_HEX_AMP|JSON_HEX_APOS); ?>
</script>
// overkill?
<script type="application/json">
<? echo htmlspecialchars(json_encode($value, JSON_HEX_QUOT|JSON_HEX_TAG|JSON_HEX_AMP|JSON_HEX_APOS), ENT_QUOTES, 'UTF-8')); ?>
</script>
As discussed in:
When used correctly, is htmlspecialchars sufficient for protection against all XSS?
Is json_encode Sufficient XSS Protection?
Json: PHP to JavaScript safe or not?
Is there any additional protection htmlspecialchars() would provide in this case above? And if so, would the reverted appliance json_encode(htmlspecialchars());
instead of htmlspecialchars(json_encode());
also work? (As I apply htmlspecialchars()
on all strings of the user data object beforehand and would apply json_encode()
later only for strings embedded in script tags.)
Additional Question:
I use htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
on all of my output strings containing user data. And my website saves extensive user data varying from strings containing emails, URLs, special characters, e.t.c.
Apart from HTML tags, will this break any other format and distort the correct display for the end-user? Are there specific occurrences on which I should put my focus?
For example, I saw that urlencode()
should be used when handling unsafe variables that will be placed within an URL, but this is not relevant in my case as I only save complete static URLs provided by users. But could htmlspecialchars()
affect breaking these static URLs?
Thank you for your time!