Is PHP's json_decode() secure as opposed to eval()? The eval() function can run code, but does json_decode() do that as well?
Asked
Active
Viewed 2,126 times
2 Answers
7
Since JSON can only represent data, json_decode
will not execute php code.
However, just like any other function, the implementation of json_decode
could be buggy and allow arbitrary (binary, not (only) php) code execution, for example with a buffer overflow. Due to the relatively simple and widely used code, this is unlikely, and there is nothing you can or should do in a php program to mitigate that.

phihag
- 278,196
- 72
- 453
- 469
-
1+1 for bugs. PHP has not had a good security history, especially string handlers many of which have allowed arbitrary memory access. See the information in the question Exploitable PHP functions http://stackoverflow.com/questions/3115559/exploitable-php-functions/3451100#answer-3697776. Certainly on PHP versions less than 5.2.9 a malicious attacker can cause a denial of service using json_decode(); see CVE 2009-1271 http://osvdb.org/52486 I would always try and perform at least a perfunctory form of validation yourself on completely untrusted data. – Cheekysoft Sep 13 '11 at 11:20
-
1This is not a helpful answer. The question is exactly whether `json_decode` might be buggy and allow arbitrary code execution. You didn't answer the question. – D.W. Sep 16 '11 at 23:50
-
D.W. Since the OP explicitely mentioned `eval` as a negative example (which is *not* intended to allow arbitrary code execution, just arbitrary *php* code execution), I don't think he considered bugs in the php implementation. Also, unless I'm totally misreading your comment, the second paragraph of this answer answers exactly "whether `json_decode` might be buggy and allow arbitrary code execution", with "yes, just like any other function". I'm puzzled as to what could be improved to clarify this answer. Can you give a hint? – phihag Sep 17 '11 at 00:01
1
eval() and json_decode() are two different functions, i don't know why you think they are similar. One evaluate a string as PHP code and the other decodes a JSON string. Nothing is executed when json_decode
is run.

aziz punjani
- 25,586
- 9
- 47
- 56
-
1Perhaps the OP is confusing eval() in PHP with eval() in Javascript. In Javascript eval() does what json_decode() does in PHP (turn JSON into an object) in addition to being able to evaluate and execute a string as code. – Jason Dean Sep 12 '11 at 23:45