Is it possible to write javascript in php heredoc syntax? - javascript

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.

Related

<br> between two variables in javascript with PHP

I create with php, a JavaScript file where inside there are two variables.
I want that two variables are on two different lines, maybe using a tag
The problem is that the output on the browser works, but inside the file.js the two variables are on the same line, and between a variable and the other there is (in text)
$javascriptContent = json_encode($var);
$settimana = "hello";
$javascriptContent = 'var settimana= "'. $settimana .'"; <br> var reports = '. $javascriptContent . ";";
file_put_contents($path, $javascriptContent);
works only on browser in the file no
I tried also with:
<br />
\n
nut nothing :(
You can't use \n inside single-quoted strings in PHP to form newlines. Escape the double quotes instead:
$javascriptContent = 'var settimana= "'. $settimana ."\";\nvar reports = ". $javascriptContent . ";";
JavaScript doesn't have HTML tags. It just has JavaScript code. What you're looking for is a newline character, not an HTML tag. Something like this:
'var settimana= "' . $settimana . '";' . "\r\n" . 'var reports = '. $javascriptContent . ";"
(Note the use of a double-quoted string to interpret the newline, as a single-quoted string won't interpret it and just treat those as literal characters.)

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

PHP parses JavaScript content inside heredoc

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

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>

Assigning the content of a txt file on server to a javascript variable

Here is my problem (which is rather simple).
How can I assign the content of a file on my server to a javascript variable ?
Here is what I tried so far:
var count= <?php echo file_get_contents("compteur.txt");?>
But it doesn't funciton. BTW: I spent two hours on google already.
If content of the file is not not a numeric value then you have to use ' or " as below
var count= '<?php echo file_get_contents("compteur.txt");?>';
Simply outputting the file's contents in between single quotes will present a lot of pitfalls. If you're using PHP 5.2 or higher, you can use json_encode, which should be a lot more foolproof:
var count = <?php echo json_encode(file_get_contents("compteur.txt")); ?>
json_encode will take care of surrounding the value in quotes, so you do not need to put quotes before and after the PHP snippet.
On versions of PHP before 5.2, you can use this less robust technique for escaping the value:
function escapeJsonString($value) { # list from www.json.org: (\b backspace, \f formfeed)
$escapers = array("\\", "/", "\"", "\n", "\r", "\t", "\x08", "\x0c");
$replacements = array("\\\\", "\\/", "\\\"", "\\n", "\\r", "\\t", "\\f", "\\b");
$result = str_replace($escapers, $replacements, $value);
return $result;
}
Source

Categories

Resources