Is it safe to do this? PHP's json_encode and javascript

Viewed 888

I've been searching around for security concerns about using PHP json_encode inside javascript context but I'm not exactly satisfied with the results

I got a lot of warnings about doing this but they always assume that I was going to inject data from the json_encode object directly to HTML without any type of sanitizing at all

So, I want to know if this and only this little snippet presents any security issues (like xss attacks etc)

<?php 
$obj = isset($_POST['js']) ? json_encode($_POST['js']) : false;
if ($obj === false) $obj = '{}';
?>
<script>var x = <?php echo $obj ?>;</script>

EDIT:
Changed the snippet to handle json_encode returning false

3 Answers

With that line of code

var x = <?php echo $obj ?>;

...the server application echoes back the data that was submitted to it via the "js" key. It will be client that sent it that will receive it, so if in some way it is malicious, it will be that same client dealing with the consequences.

The actual sending to the server is in fact the irrelevant part of the chain: if one has the data to submit, one can also assign it to the variable x directly without the server's interference (e.g. through browser's dev tools).

It would be a different story if in PHP you would use the data to manipulate a server database, call a service, or otherwise change the application's state, and you would not first validate that data.

As to the use of json_encode: if indeed you verify that the argument is valid JSON (by checking that the return value is not false), it will produce a valid JavaScript object literal. The known cases of incompatibility (characters U+2028 and U+2029) will not occur, as by default json_encode escapes these characters.

It is correct as per coding. However you have to validate the variable x should not be empty or the posted value.

<script>var x = "<?php if(isset($_POST['js']))
{   
   echo json_encode($_POST["js"]);
}";
</script>

Sometimes json_encode returns false, if return it that js expression will broke. this will works safer.

<script>var x = JSON.parse(<?php echo (json_encode($_POST["js"]) ? json_encode($_POST["js"]) : '{}'));</script>

if json_encode returns false, var x will get just empty object.

Related