PHP: literal \n rather than new line - php

I have a php var which, when echoed, writes a JS function into the source of a page. The function loops through a CSV and so it has the following line within it:
$str="var lines = data.split('\n');";
At the present time, when echoed, I get this 'correct' JS written into the source:
var lines = data.split('
');
Instead, I want to echo the literal string \n into the source of the page.
Can anyone point me in the right direction? Thanks.

Escape the slash.
"\\n"
So that it is treated as a slash instead of an escape character.

Try this:
$str="var lines = data.split('\\n');";

you can escape \ like this: \\.
But I would put the whole JS functionality into a .js file, include that from the generated HTML, and call the specific function when needed. And generate a minimalistic js code, like var config = {....} if I have to communicate some page related information.
You almost never need dynamically generated JS code. It's a lot harder to read and you're wasting CPU and network bandwidth...

Either the solutions in the earlier answers, or invert the quotes by using single quotes as the PHP string delimiter:
$str='var lines = data.split("\n");';
Or escape the inner quotes, if you want to keep single quotes for javascript as well when using single quotes as the PHP string delimiter.
$str='var lines = data.split(\'\n\');';
See the docs on quoted strings in PHP as well about how single quoted strings and double quoted strings behave differently.

Related

Backslashes breaking string in PHP

I have an issue. I'm trying to write a string with ASCII text like this: '/\'. But whenever I do that the backslash screws up the code by canceling out the quote defining it a string therefore screwing it up. Is there anyway to cancel out the backslash so it doesn't cancel out the quote? Thanks guys!
The \ is special character, that says: 'The next character has special meaning'.
So if you want to dispaly \ you should write... \\ to get one \ in output
It would be very helpful to show what you have tried, but this will produce the exact output you requested (as shown by SO)
echo '\'/\\' . "'\n" ;
'/\'
It should also give you an idea of how backslash escaping works in different types of strings.
A great solution when writing stuff like that is HEREDOC. Inside a heredoc block you don't need to worry about escaping anything, it will just be text.
For example:
echo <<<TEXT
/|\/|\/|\/|\/|\/|\/|\/|\/|\/|\
TEXT;
There is one catch. PHP will break if you don't align the echo at the start of the line, or if the TEXT; is not aligned at the start of the line.
Heredoc can also be assigned to a variable, like so:
$var = <<<SOME_MORE_TEXT
/|\/|\/|\/|\/|\/|\/|\/|\/|\/|\
SOME_MORE_TEXT;
Finally, HEREDOC preserves tabs and spaces. Which also might come in handy when doing ASCII art.
Refer to: http://php.net/manual/en/language.types.string.php for more information.
You only need to escape the final one when using single quotes.
$var = 'backslash\backslash\backslash\\';
// output is:
// backslash\backslash\backslash\

PHP function for removing and adding back in \'?

I have a search form for finding restaurants. I got it handling apostrophe's just fine for the actual search, but when they're passed as \' into Javascript for mapping it's killing my maps.
Example:
xml_searchresults.php?cityID=1&type=1&searchTerm=Sonny\'s Real Bit BBQ
For a simple fix, in PHP I'm trying to go from:
$searchTerm = "Sonny\'s Real Bit BBQ" (in the original PHP file)
Then replace the \' with [slashapostrophe]:
$searchTerm = "Sonny[slashapostrophe]s Real Bit BBQ" (to be fed to javascript)
and then replace the [slashapostrophe] back with \':
$searchTerm = "Sonny\'s Real Bit BBQ" (in the PHP generated XML map marker file)
I tried str_replace but the quotes and slashes confuse it. Thanks!
php function addslashes() to quote string with '\' and stripslashes() to remove extra '\' symbols ( to unquote quoted string)
You are looking for stripslashes(): http://php.net/manual/en/function.stripslashes.php

Escaping string before assigning to innerHTML echoed by PHP

I'm encountering a problem involving escaping character that I think it's not simple at all. If this is done in javascript, nothing to say but the context is using echo command (in PHP) to write javascript code like this:
echo "<script>document.getElementById('spanID').innerHTML=\"$x\"</script>";
$x is a variable in PHP environment, which can contain both single and double quotes. What I do here is:
1. Keep the $x not change, and if $x contains any double quote, the above code won't work, the text echoed may look like:
<script>document.getElementById('spanID').innerHTML="leftside"rightside"</script>;
I supposed $x = leftside"rightside, and you can see it surely won't work.
Escape the double quotes in $x (change all " to "), then the text echoed may look like this:
document.getElementById('spanID').innerHTML="leftside"rightside";
The " won't be converted to " when it is assigned to innerHTML attribute of a Span (for e.g), so instead of my want, the innerHTML of my SPAN should be leftside"rightside, it will be leftside"rightside.
If I change the " to ' in the original echo, like this:
echo "<script>document.getElementById('spanID').innerHTML='$x'</script>";
It is the same because $x here can contain both single and double quotes.
I don't find out any other ways to escape quotes in this case. Could you please help me out?
Thanks!
You need to put between the quotes a string that is a valid string of JavaScript containing valid (and safe) HTML.
Your best option is to not use innerHTML and instead use document.createTextNode which means you only need to slash-escape the content.
Otherwise, you need to HTML escape, then slash escape the content. For correctness, your slash-escaping function should escape at least double-quotes, backslashes, and all JavaScript newlines (U+A, U+D, U+2028, U+2029). I believe PHP's addslashes does not handle U+2028 or U+2029 by default but How to escape string from PHP for javascript? has some alternatives.
To put it all together:
$x_escaped = json_encode($x, JSON_HEX_TAG);
echo "<script>document.getElementById('spanID').appendChild(document.createTextNode($x_escaped))</script>"
should do it. The JSON_HEX_TAG makes sure that $x_escaped will not contain </script> or any other content that prematurely ends your script tag. </script> will instead become \u003c/script\u003e.

How to insert backslashes before all line breaks in a string?

I am building multi-line strings in PHP that need to be used in Javascript functions, so I echo out the strings and they appear where they should, but the problem I'm having is that Javascript multi-line strings must have a backslash \ at the end of each line.
Aside from hard-coding the backslashes in (which I can't do since the strings are used outside of the Javascript functions, too) how can I add a backslash before each line break in the string?
Run the string through the json_encode function to generate a JavaScript string. Don't try to write your own routine to make a string safe for JS.
str_replace("\r\n","\\\r\n",$str)

Saving source code from HTML textarea to file

I am saving C++ code from a textarea of an HTML form using PHP.
The problem is if my code is like below,
printf("%d\n");
printf("%d\n");
the code that is saved to the file is like this:
printf(\"%d\\n\");\nprintf(\"%d\\n\");
I want the original code to be saved in the file. If I use,
$sourceCode = str_replace('\n',"\n", $sourceCode);
$sourceCode = str_replace('\"',"\"", $sourceCode);
the result is like below (saved in the file):
printf("%d\
");printf("%d\
");
It is clear that replacing \n in the source code replaces all the HTML created \n along with the \n that user gave as input (the original text). The only difference is user's input has an additional \ before the \n, that is \\n.
How can I resolve the problem such that only the implicit escape characters will be replaced, but the explicit escape characters, that the user wrote himself, will not be changed?
As mentioned by KenB, we need to see the PHP code that you are using to process the form input.
Processing Form Input
It looks to me like addslashes has been used on the form input.
If you are doing that in your code, don't. This is not the proper way to process form input. Instead, you should use the correct function (such as htmlspecialchars or mysqli_real_escape_string) to escape the input before you use it. Read about addslashes.
If you are using an older version of PHP where magic_quotes_gpc is on by default, then you should fix that. Read about 'Disabling Magic Quotes'.
Stripping Out the Slashes
If you have no control over the code that is adding the slashes, then you can remove them with a simple PHP function called stripslashes.
$sourceCode = stripslashes($sourceCode);
Read about stripslashes.
Understanding Escape Sequences
Your str_replace code shows a lack of understanding about escape sequences and/or a lack of understanding about single vs double quotes.
In the following code, a literal \n is replaced with a line break. With the double quotes, PHP interprets the \n as an escape sequence rather than a literal string.
$sourceCode = str_replace('\n',"\n", $sourceCode);
What you want is to replace a literal \\n with a literal \n. Note that to specify a literal backslash it must be doubled; hence the triple backslash you see below.
$sourceCode = str_replace('\\\n', '\n', $sourceCode);
And although this next line accomplishes what you wanted...
$sourceCode = str_replace('\"',"\"", $sourceCode);
...it could have been written differently. The following code is easier to read, saves you having to escape the literal ", and doesn't require PHP to interpret the string.
$sourceCode = str_replace('\"', '"', $sourceCode);
I've given the above code as examples to explain how PHP interprets escapes sequences, but don't use them. Either avoid adding the slashes in the first place or strip them using the proper function, as explained in the first part of this answer.
Read more about escape sequences and quoting strings.
The Literal \n Between Lines
I'm not sure what you are doing to add the literal \n between the lines. We'd need to see your code. But to remove it after the fact, you could try the following
$sourceCode = str_replace(';\n', ";\n", $sourceCode);
Of course, then you'd likely need to correct other C++ end-of-line sequences. So it is better to not add it in the first place.

Categories