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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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
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
would then reach the browser as
Which clearly results in doSomethingEvil() being executed. By escaping any html tokens you end up sending something like
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)