I have a stdClass
object in PHP, something like
$o = new stdClass;
$o->foo = $bar
The variable $bar
contains an untrusted string.
Is the following PHP template code sufficient XSS protection
<script type="text/javascript">
var o = <?php echo json_encode($o); ?>;
</script>
My initial gut reaction is that is is safe, as encoding an object as JSON will ensure any potential javascript exploits will be rendered inert by being included as JSON string property objects. Something like this
$o = new stdClass;
$o->foo = "<script type=\"text/javascript\">alert(document.cookie)</script>";
?>
<script type="text/javascript">
var o = <?php echo json_encode($o) ?>;
</script>
Resulting in output like this
<script type="text/javascript">
var o = {"foo":"<script type=\"text\/javascript\">alert(document.cookie) <\/script>"};
</script>
If this is known unsafe, is there's a standard, mature way of serializing a simple stdClass
object to a JSON string for use in a the <script/>
portion of an HTML document.
In anticipation of the first quick answer, I realize that stripping out any HTML tags, or otherwise XSS filtering each element of the JSON object would work, but I'm looking for a concise way of doing this. Similar to how this
//$eBar = addslashes($bar);
$sql = sprintf("SELECT * FROM table WHERE foo = '%s'",mysql_real_escape_string($bar));
and this
$sql = $db->select('SELECT * from table where foo = ?', $bar);
are (in most contexts) functionally equivalent, but the later is considered better, more secure code since the end programmer user doesn't need to worry about escaping schemes.