I have a
stdClass object in PHP, something like
$o = new stdClass; $o->foo = $bar
$bar contains an untrusted string.
Is the following PHP template code sufficient XSS protection
Resulting in output like this
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 = sprtinf("SELECT * FROM table WHERE foo = '%s'",mysql_real_escape_string($bar));
$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.
Seems as through the best answer to this question lies in another question.
However, passing in a raw string to JSON encode can lead to the usual litany of XSS attacks, the following combination of constants is suggested.
var v= <?php echo json_encode($value, JSON_HEX_QUOT|JSON_HEX_TAG|JSON_HEX_AMP|JSON_HEX_APOS); ?>;
or ensure the variable passed to
json_encode is really an object.