Is it safe to do this? PHP json_encode and javascript

I was looking for security issues when using PHP json_encode inside a javascript context, but I am not completely satisfied with the results

I got a lot of warnings about this, but they always assume that I am going to enter data from the json_encode object directly into HTML without any disinfection at all

So, I want to know if this and only this small fragment represents any security problems (for example, 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 fragment to handle json_encode returning false

+4
source share
4 answers

With this line of code

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

... , "js". , , , , - , , .

: , x (, dev),

, PHP , , .

json_encode: , JSON (, false), JavaScript. ( U+2028 U+2029) , json_encode .

0

json_encode() . JSON . JSON promises. , , . + PHP JSON- , ASCII, JSON.

, :

var x= <?php echo json_encode($value, JSON_HEX_QUOT|JSON_HEX_TAG|JSON_HEX_AMP|JSON_HEX_APOS); ?>;

  • , .
+1

This is correct according to the encoding. However, you need to check the variable xshould not be empty or published value.

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

Sometimes json_encode returns false if it returns so that the js expression breaks. it will work 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 only get an empty object.

-1
source

Source: https://habr.com/ru/post/1689603/


All Articles