As far as I know it is considered bad practice to eval()
JSON objects in JavaScript, because of security. I can understand this concern if the JSON comes from another server.
But if the JSON is provided by my own server and is created using PHP's json_encode
(let us assume it is not buggy), is it legitimate to simply use eval()
to read the JSON in JS or are there any security problem I currently can't think of?
I really don't want to deal with dynamically loading a JSON parser and would be glad to simply use eval()
.
PS: I will obviously use the native JSON
object if it is available, but want to fall back to eval()
for IE/Opera.
There are a number of ways that your security may be compromised.
- Man in the middle attacks could theoretically alter the contents of data being delivered to the client.
- Your server traffic could be intercepted elsewhere and different content could be provided (not quite the same as a MIM attack)
- Your server could be compromised and the data source could be tampered with.
and these are just the simple examples. XSS is nasty.
"an ounce of prevention is worth a pound of cure"
In your scenario, the question becomes, where is PHP getting the javascript to execute from? Is that channel secure, and free from potential user manipulation? What if you don't control that channel directly?
Besides the obvious security issues:
- Native JSON is faster
- You don't need to "load" a JSON parser it's just another function call to the JavaScript engine
Tip:
in asp.net using JSON is considered bad becuase parsing of DateTime differs between the server and the client so we use a special function to deserialize the date in javascript. I'm not sure if PHP has the same issue but its worth mentioning though.
check out this:http://blog.mozilla.com/webdev/2009/02/12/native-json-in-firefox-31/
so at least for firefox you can use the built in json parser
Seriously? Some of the guys here are paranoid. If you're delivering the JSON and you know it's safe, it's ok to fallback(*) to eval();
instead of a js lib for IE. After all, IE users have much more to worry about.
And the man-in-the-middle argument is bullsh*t.
(*) the words fallback and safe are in bold because some people here didn't see them.