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.
Malicious code : invoking eval can crash a computer. For example: if you use eval server-side and a mischievous user decides to use an infinite loop as their username. Terribly slow : the JavaScript language is designed to use the full gamut of JavaScript types (numbers, functions, objects, etc)… Not just strings!
You are more vulnerable to attacks if using eval : JSON is a subset of Javascript and json. parse just parses JSON whereas eval would leave the door open to all JS expressions.
The eval() function in JavaScript is used to take an expression and return the string. As a result, it can be used to convert the string into JSON.
This JSON parser does not attempt to validate the JSON, so may return a surprising result given a syntactically invalid input, but it does not use eval so is deterministic and is guaranteed not to modify any object other than its return value. There are a number of JSON parsers in JavaScript at json.org.
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?
There are a number of ways that your security may be compromised.
and these are just the simple examples. XSS is nasty.
"an ounce of prevention is worth a pound of cure"
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