I have code that gets some text from database and inserts it inside javascript var. This is the code:
<script>
var = <?php echo $var ?>
</script>
When the page is loaded, var looks like this:
<script>
var = "This is first line
This is second
This is third..."
</script>
Is there a way to dynamically add a backslash after each line?
EDIT :
I am using PHP to echo the text and I want to manipulate it inside javascript
How you escape something depends on the context you use it in.
If you don't want line breaks to be included literally in the HTML output, you have to encode them as '\n'. But if a newline character is preceded by a slash in the output, e.g.:
\<newline>
then you have to escape the backslash too. Otherwise, escaping the newline only will actually just escape the backslash:
\\<newline>
So to backslash a newline, you must backslash the backslashes first and then backslash the newlines:
\\\<newline>
We also have to watch out for XSS (cross-site scripting) attempts. If someone inserts a </script> into your string, then they could prematurely end your script block (even though it's in a JS quote!) and change the behavior of your page. To prevent this, we backslash the forward slash so that it doesn't read as a literal </script> to the HTML parser. (See below.)
The three PHP functions that are most useful for this sort of thing are addslashes, htmlspecialchars and str_replace.
To escape for a JS string (and escape the newline characters), you can use the following function:
<?php
function escapeForJSString($var) {
return str_replace(
"/" // escape forward slash to help prevent XSS
, "\\/"
, str_replace(
"\n" // escape newline
, "\\n"
, addslashes($var) // escape single quotes, double quotes, backslash, and null byte
)
);
}
?>
In your code:
<?php
$var = "You can find the file at C:\\Program Files\\Cool Program\\Preferences.txt > colorScheme
if you want to change it.</script>";
?>
<script type="text/javascript">
var lines = "<?= escapeForJSString($var) ?>";
alert(lines);
</script>
Output:
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<script type="text/javascript">
var lines = "You can find the file at C:\\Program Files\\Cool Program\\Preferences.txt > colorScheme\n if you want to change it.<\/script>";
alert(lines);
</script>
</head>
<body>
</body>
</html>
A couple notes:
You have to have a variable name, not just var.
Put quotes around strings.
You can either use <?php echo $var ?> or <?= $var ?> (short_open_tag must be enabled in your php.ini file if you're using a version of prior to PHP 5.4).
Just split the variable into new lines with whatever delimiter you like:
<?php
$var = "This is line 1|##|This is line 2|##|This is line 3";
?>
<script type='text/javascript'>
var lines = "<?=$var?>";
var res = lines.split("|##|");
res.forEach(function(entry) {
alert(entry + "\\");
});
</script>
Related
I have a for loop in which I am printing out content on a web page. Anything with a line break in the database will not work with innerHTML.
Here is the process of how to get a string from the db:
1. Submit a form with text thats gets queried into the database.
2. For loop which displays all the contents in the database using an array,
say $content[i].
value.innerHTML works with any strings that don't have a line break.
For example, in the db:
Hello
there
----- Will not work.
Hello there
----- Will work.
I have tried using regexes to get a line break and change them to br and such, but inner html will not display content with line breaks. Only those without.
My code that I am using:
var commentSection = document.createElement("div");
var str = '<?php echo $comment['contents'];?>';
str = str.replace(/\r\n?|\n/g, '<br />');
var userCommentData = document.createElement("div");
userCommentData.innerHTML = str;
commentSection.appendChild(userCommentData);
And a more clearer picture of the error I am having:
A step of a query string
Use following functions:
htmlentities:Convert all applicable characters to HTML entities
nl2br Inserts HTML line breaks before all newlines in a string
Or maybe change your sql query with TRIM function as used in link
Use backtick character ( ` ) for multiline string in javascript.
use this line { Replace backtick with ( ` ) }
var str = backtick <?php echo $comment['contents'];? > backtick ;
insted of this line
var str = '<?php echo $comment['contents'];? >';
I'm trying to output Javascript code heredoc syntax and I want it to be printed out with the PHP print_r function. Is it possible to do that?
PHP:
<?php
function printR($val){
echo "<pre>";
print_r($val);
echo "</pre>";
}
$str = <<<EOT
var msg = "Hello my name is ";
var name = "Jermaine Forbes";
function writeIt(m,n){
console.log(m+n);
}
writeIt(msg,name);
EOT;
printR($str);
?>
(by #FirstOne: I kept EOT; idented since there was* a comment about it)
Yes you can. If you expect to have only Javascript in the string (no PHP variable), I would use nowdoc instead of heredoc (use single quotes around the opening EOT
$str = <<<'EOT'
var msg = "Hello my name is ";
var name = "Jermaine Forbes";
function writeIt(m,n){
console.log(m+n);
}
writeIt(msg,name);
EOT;
Note also that the closing delimiter must be alone on the final line. You can't have any space before or after it. Your code didn't work because you have indented EOT;. From the docs:
Warning: It is very important to note that the line with the closing
identifier must contain no other characters, except a semicolon (;).
That means especially that the identifier may not be indented, and
there may not be any spaces or tabs before or after the semicolon.
I have a pretty complex problem.
I'm using PHP to parse a CSV file to an array and then
var array = <?php echo json_encode( $array ) ?>;
to pass it to the Javascript array.
array is 2-dimensional, like so:
var array = [["\/\\ssa","14104","26","2113","0","867","28083","15","43695"],
["Yee","8661","24","2215","0","991","25245","15","49086"],...]
Now sometimes there seems to be a problem with backslash escapes in the username when it is structured like this:
["username\","sth","sth",...], so when the username ends with a backslash \ .
The output will be:
username", sth, sth, ...
But this is only the first element of the sub-array, the other 8 places are empty.
I have already tried to fix it with a loop replace, but I don't know how to add \" as search value. Is this impossible to do in JS since \" always escapes? Already tried charAt() to compare the last character with the backslash, but no success. Do I have to replace it before passing it to JS, in PHP?
The Parse function is this, if it's important:
<?php>
$url = "data.csv";
$csvData = file_get_contents($url);
$lines = explode(PHP_EOL, $csvData);
$array = array();
foreach ($lines as $line) {
$array[] = str_getcsv($line);
?>
Here a JSfiddle you can play with: https://jsfiddle.net/cLmbe0qf/
You just need to replace backslashes by an html special character :
foreach ($lines as $line) {
$line = str_replace("\\", "\", $line);
// ...
}
This is a little bit more tricky since you have to parse the javascript into an object/array. Anytime you do this, the backslash is parsed out. To avoid doing this you need to store the value in the HTML page or use String.raw to get the literal version of the string.
One way to implement it is to put the the string in the html and get the value of a hidden textarea. (you could store it anywhere, i just chose textarea). You then pass it through this javascript function slashParse which will replace all slashes with ~{}~ then run the javascript parsing algorithm, then replace the ~{}~ back to the backslashes.
function slashParse(target) {
var value = document.getElementById(target).value;
var replacedVal = value.replace(/\\/g, '~{}~');
var parsedVal = JSON.parse(replacedVal);
var mappedVal = parsedVal.map(function(item) {
return item.replace(/~{}~/g, '\\');
});
return mappedVal;
}
var parsed = slashParse('input');
console.log(parsed)
document.getElementById("test").innerText = parsed;
<body>
<div id="test"></div>
</body>
<textarea style="display:none" id="input">["use\rna</textarea><textarea>me\\","2","3","4"]</textarea>
What echoing it out onto the page might look like would be like this.
<textarea style="display:none" id="php-part">
<?=json_encode(htmlentities($array,ENT_NOQUOTES))?>
</textarea>
This is only one solution of a few more. Another option is to do more parsing on the php side of things. The problem you will run into, is that at some point you need to run the string through the JavaScript parsing program. When that happens you cannot have any backslashes. Then after you run it through the parsing, you will have to convert all hidden backslashes back to backslashes.
The one problem with this method is that if there is anywhere EVER where ~{}~ is being placed in the string, it will be converted to backslashes afterwards. Something you can do in order to make it more aloof is to make the string backslashes get turn into even more obfuscated. Such as ~{BACKSLASH_ESCAPE}~
Could you tell me why this is not working ?
<html>
<body>
<?php
$var1 = "hello";
echo $var1;
?>
<button type="button"
onclick="document.getElementById('demo').innerHTML = <?php echo(json_encode($var1)); ?>;">
HI</button>
<p id="demo"></p>
</body>
</html>
What should I do to be able to read the php variable from JS ?
Thanks
It is a string. The 's needed to added properly around the string.
onclick="document.getElementById('demo').innerHTML = '<?php echo(json_encode($var1)); ?>';"
As $var1 is string, you need to wrap that in quotes.
AS $var1 is string and not array or object, json_encode is not required.
Use quotes around the string(See the marked positions for quotes):
onclick="document.getElementById('demo').innerHTML = '<?php echo($var1) ?>'">
// ^ ^
Despite there are many answers, I will give my 2 cents about what I think the OP was thinking:
The basic idea was using json_encode to make the hello string to print "hello" instead of hello. The problem is actually that it will result in:
onclick="document.getElementById('demo').innerHTML = "hello";"
Which is NOT valid because of double quotes inside of double quotes.
Hence he can keep using json_encode if he wants to, as long as he changes the double quotes to single quotes:
onclick='document.getElementById("demo").innerHTML = <?php echo json_encode($var1); ?>;'
^ <-- single quote ^----^ <-- double quote here single there too --> ^
This should result in a valid output, which is:
onclick='document.getElementById('demo').innerHTML = "hello";'
<?php
$javascript = <<<EOT
<script type="text/javascript">
function test () {
return 'test test test \n test test test';
}
</script>
EOT;
echo $javascript;
?>
The \n above is parsed as newline by PHP, generates HTML source like the following
return 'test test test
test test test';
and this results in a JavaScript syntax error: unterminated string literal.
I have a big chunk of JavaScript code, so I don't want to wrap them like
$javascript = "<script type=\"text/javascript\">\nfunction test()...\n";
and actually the JavaScript code is not directly echo'd to the page, it is passed to another function, this is why I need a PHP variable.
So how can I define a PHP variable that contains a big chunk of JavaScript code whitout causing problems?
Is there a way like if / endif?
<?php if (condition): ?>
html code...
<?php endif ?>
Option 1: Use a NOWDOC, which is to HEREDOCs as ' single quotes are to " double quotes.
$javascript = <<<'EOT'
...\n...
EOT;
Option 2: Escape the special character:
$javascript = <<<EOT
...\\n...
EOT;
My code:
$javascript = <<<'EOT'
<script type="text/javascript">
$demo = 'test';
alert($demo);
</script>
EOT;
echo $javascript;
If i use 'EOT' then my code in javascript working well, but i use EOT then my code will understand $dem is variable in PHP