saiedmomen
saiedmomen

Reputation: 1441

why eval() doesn't work with output of JSON.parse()?

I want to showcase some javascripts. To do so I read the contents of .js files with php file_get_contents() then json_encode() and echo the results, then on the fore end I read the result through $.get() and then I do a JSON.parse() on the results(I have tried not parsing it) but still eval() doesnt work on the result.

Oddly enough if I copy the result of json_encode() and paste it in a js variable then eval() works!

What did I do wrong?

Server side:

$name=$_GET['name'];
$t=  file_get_contents('../graphics/'.$name);
$t=  json_encode($t);
echo $t;

client side:

$.get("php_lib/readGraph.php",{ name:name}, function(data, status){
                    if(status){
                       eval(JSON.parse(data));
                       }
                    else {
                        alert('Ajax error');
                    }
                    });

Upvotes: 0

Views: 233

Answers (1)

Schlaus
Schlaus

Reputation: 19212

There's no need to encode your code to json. You're not passing on formatted data like variables, you're outputting full javascript code. I'd try simply removing the json parts.

Hopefully the PHP you pasted was just a sample, and you are doing serious verification before allowing people to output files from your server. Having a path specified in your code is nowhere near enough, since that can easily be circumvented by simply adding .. to the input. A hacker could then output absolutely everything the user your webserver is running as has read access to. Even outside your web root. That out of the way, a more efficient way to output a file would be to use readfile().

Upvotes: 2

Related Questions