user324289 user324289 - 1 year ago 81
Javascript Question

XSS : Creating a javascript object using PHP's json_encode

Is this 100% safe against XSS?
If not, can you please provide example bad string text showing me why it is not.

$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)).";";


Answer Source

In short, it's safe. Possible XSS would require escaping from the javascript string (") or script (</script>). Both strings are properly escaped:

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

This is the the part about direct injection. Your application should take in account that some array elements may be missing. Another possibility is that an array element is not the type you would expect (e.g., an array instead of a string)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download