Reputation: 2779
I need to do the following:
<?php
$userContentFromDatabase = 'Some string that may contain "double quotes" ';
?>
<script type="text/javascript">
var userContent = "<?= $userContentFromDatabase ?>";
</script>
How can I avoid the double quotes from interfering with the JavaScript code?
Upvotes: 0
Views: 166
Reputation: 4416
You need more escaping than that if you want to safely output user data in a javascript variable. See rule 3 https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet#RULE_.233_-_JavaScript_Escape_Before_Inserting_Untrusted_Data_into_JavaScript_Data_Values
Upvotes: -1
Reputation: 12059
Use json_encode()
on the PHP side and return an object as this will take care of all of the slashes and what not that might break your code.
Or just add slashes using str_replace()
if you think that the only problem area will be the double quotes.
Upvotes: 2