Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing php string with multiple lines to a javascript function/variable

I'm working on someone else's website and it has a very stupid logic! Anyway, there is a php variable which contains a string which comes from database.

$x = ' aaaa
bbb

ccc


gggg ';

and I need to feed this string to a javascript function:

<script>

var x = "<?php echo $x ; ?>";
some_function(x);

</script>

As you know I end up with an error because a javascript variable cannot contain multiple lines without joining them together like this:

var x = ' i '+
        ' have '+
        ' different lines'; 

How can I do this? It doesn't matter if it removes the lines or formats it properly, I just want to get rid of this error.

like image 248
max Avatar asked May 20 '13 23:05

max


1 Answers

Pass the string into json_encode to properly escape it. If you're outputting to an HTML document, make sure to pass JSON_HEX_TAG as part of the options, to escape < and > and prevent a malicious user from ending your </script> tags early and introducing an XSS exploit.

like image 161
Gray Avatar answered Sep 17 '22 22:09

Gray