0

Consider the code below to send a json string to js from php,

<?php
    $str = "<!--<script>"; // This is from user input
?>

<script>
   var json_str = <?= json_encode($str) ?>;
</script>

The string will break the HTML, and the way to solve it is via something like the old school comment hack, e.g.

<script>
<!--
   var json_str = <?= json_encode($str) ?>;
//-->
</script>

Are there any alternative?

3
  • 1
    The example shown will not result the expected way, anyway, if you need to escape it, you can use htmlentities Commented Aug 18, 2014 at 11:24
  • var str = <?= json_encode(strip_tags($str)); ?>; not an option? strip_tags, or even a simple str_replace(array('<!--', '-->), '', $str)` should do Commented Aug 18, 2014 at 11:24
  • @RoyalBg: Read the question: the OP is aware of the problem Commented Aug 18, 2014 at 11:25

1 Answer 1

5

You can use the flag JSON_HEX_TAG, so that < and > will be encoded as \u003C and \u003E respectively.

json_encode($str, JSON_HEX_TAG)
Sign up to request clarification or add additional context in comments.

1 Comment

+1 This is the best way - as per the OWASP XSS (Cross Site Scripting) Prevention Cheat Sheet - Except for alphanumeric characters, escape all characters with the \uXXXX unicode escaping format (X = Integer)..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.