XSS: creating a javascript object using PHP json_encode

Is it 100% safe against XSS? If not, can you give an example of a bad line of text showing me why this is not so.

<html>
  <body>
    <script>
      <?php
        $bad = "some bad string.  please give example text that makes the below unsafe";
        echo "var a = ".json_encode($bad).";";
        echo "var b = ".json_encode(array($bad)).";";
      ?>
    </script>
  </body>
</html>

Thanks.
+5
source share
2 answers

In short, it is safe. XSS may require escaping from a javascript ( ") or script ( </script>) string . Both lines are correctly escaped:

"          becomes  \"
</script>  becomes  <\/script>

This is part of direct injection. Your application should consider that some elements of the array may be missing. Another possibility is that the element of the array is not the type you expect (for example, an array instead of a string).

+4

!!!

json_encode javascript.

:

json_encode <img src=# onerror=alert(1)>, brower. xss.

htmlspecialchars.

+2

All Articles