Howard
Howard

Reputation: 19825

Proper way to escape json data in PHP without using JS comment hack

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?

Upvotes: 0

Views: 448

Answers (1)

C3roe
C3roe

Reputation: 96455

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)

Upvotes: 5

Related Questions