PHP parses JavaScript content inside heredoc - javascript

<?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

Related

Is it possible to write javascript in php heredoc syntax?

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.

JSON containing single quote causes syntaxerror

So I have data that needs to be fetched through php. This data should then be saved to a javascript variable in the .php file echoing the value:
$json = json_encode($requirements);
echo "<script>
var myvar = '<?php echo $json; ?>';
</script>";
The data contains a single quote which gives syntax error in Chrome:
Uncaught SyntaxError: Unexpected identifier
The page source look something like by the error:
var myvar = '<?php echo {"data":{"data":{"1":{"description":"Don' t}}}}; ?>';
where the entire string up until ""Don'" is in red.
What is the right way of keeping json_encode from failing (apart from calling the data directly to js)?
You need to escape ' chars then, for example by using backslash \:
{"data":{"data":{"1":{"description":"Don\'t}}}}
Or as you are using php you can use addslashes function
I have also experienced same problem with Single & Double quote.
You can resolve it easily by changing the single & double quote. Check below example.
$array = array(
"data" => array("data" => array ("desc" => "don't"))
);
$json = json_encode($array);
echo "<script>
var myvar = ".$json.";
console.log(myvar);
</script>";
You need to escape double quotes, Try:
var myvar = "<?php echo '{\"data\":{\"data\":{\"1\":{\"description\":\"Don\'t}}}}'; ?>";
alert(myvar)

Remove Backslash Escaping in Javascript Array

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}~

call php var inside JS

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";'

dynamically add backslash to end of string line

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>

Categories

Resources