How to escape backslashes in files - php

I am trying to work on a script but I am stuck in one place.
Eg. To get a php output I have used..
str_php = """
<?php
echo "Hello World!";
?>"""
php_file = open("index.php", "w")
php_file.write(str_php)
php_file.close()
Ok, so I get the output as it is....
<?php
echo "Hello World!";
?>
So my php code is running. all good till here. But, the problem starts from when I try using "\" and "\n" and "\r"
str_php = """
<?php
echo "Hello World!"; \n echo "How are you"; \n echo "God bless you";
?>"""
php_file = open("index.php", "w")
php_file.write(str_php)
php_file.close()
But here I dont get the output as it is.
<?php
echo "Hello World!";
echo "How are you";
echo "God bless you";
?>
And the "\" it just vanishes... at an output.
Eg. I want an output of a php hyperlink something like...
str_php = """<?php
print("$dirArray[$index]");
?>"""
php_file = open("index.php", "w")
php_file.write(str_php)
php_file.close()
and the output I get is...
<?php
print("$dirArray[$index]");
?>
The "\" is missing and the php does not run creating error.
print("$dirArray[$index]") - Original
print("$dirArray[$index]") - python output
Can any one help me out with "\", "\n", "\r" ??

Just use "\" to escape the "\" character.
Since it is common to want to have long strings containing several "\", Python also allows one
to prefix the string opening quotes if ar r (for "raw") - inside such
a string, no escaping of "\n" to chr(10) or "\t" to chr(9) happens:
>>> print (r"Hello \n world!")
Hello \n world!

You need to escape your "\" with another backslash writting it as "\\".

If you use "\n" it will be parsed and make a newline. Try to use '\n', strings enclosed in '\n' are not parsed and it should print out as you want it to.

Related

str_ireplace or preg_replace replaced break tag into \r\n

I have read this post that discuss about converting html break tag into a new line in php. Other people said it's work for them but something weird happened to me.
this is the code I use:
$breaks = array("<br />", "<br>", "<br/>");
$jawaban = str_ireplace($breaks, "
", $jawaban1);`
and this is the code they use :
$breaks = array("<br />", "<br>", "<br/>");
$text = str_ireplace($breaks, "\r\n", $text);
both insert "\r\n" into the text , why is this happening ?
screenshot:
if there's any previous post / PHP method let me know
EDIT : adding my code that echo the textbox
<-- THIS WONT WORK -->
$username = $_SESSION['username'];
$unsafenomorsoal = $_POST['nomorsoal'];
$unsafejawaban = $_POST['jawaban'];
$nomorsoal = mysqli_real_escape_string($konek,$unsafenomorsoal);
$jawabannotcut = substr($unsafejawaban,0,50000);
$unsafejawabanfirst = nl2br($jawabannotcut);
$jawaban1 = mysqli_real_escape_string($konek,$unsafejawabanfirst);
$breaks = array("<br />","<br>","<br/>");
$jawaban = str_ireplace($breaks, PHP_EOL, $jawaban1);
$_SESSION['textvaluejawaban'] = $jawaban;
and this is what echoed :
echo "<div class=\"head-main-recent-background\" style=\"background:white;width:99%;color:black;text-align:left;height:1000px;position:relative;top:130px;margin-top:10px;\">- Jawab Soal -<br/>".$jawabanerror."<br/>Nama : ".$_SESSION['username']."<br/>
<form method=\"post\" action=\"prosesjawabsoal.php\">
<input type=\"hidden\" name=\"nomorsoal\" value=\"".$_SESSION['nomorsoal']."\"/>
Jawaban : <br/>
<textarea placeholder=\"Max 40.000 Huruf\" style=\"overflow- x:none;width:99%;height:300px;\" type=\"text\" name=\"jawaban\" maxlength=\"40000\" >".$_SESSION['textvaluejawaban']."</textarea>
<br/>Captcha <br/>
<div style=\"overflow:hidden;\" class=\"g-recaptcha\" data- sitekey=\"6LfYQicTAAAAAFstkQsUDVgQ60x_93obnKAMKIM9\"></div><br/>
<button type=\"submit\" name=\"submit\" style=\"margin-top:10px;height:auto;width:auto;\">Kirim Jawaban</button>
</form>
</div>";
Note : The snippet won't work because it's php
Sorry i used snippet due to error while posting the code !
EDIT :
tried preg_replace() method but still same result
EDIT :
change title to tell that preg_replace not work
Your problem is the mysqli_real_escape_string(). The converts the "\r\n" into a string to make it safe to input into the database. Remove it completely. Instead use htmlspecialchars when you output to screen:
echo htmlspecialchars($myUnsafeVar);
Apply these rules (as a starting point, there's always possible exceptions, but in rare cases):
use mysqli_real_escape_string when inputting strings into a database. It won't do what you expect when outputting to screen - so anything that has been mysql escaped() should not appear on screen.
use htmlspecialchars (which you don't have!) when outputting to screen.
use url_encode for adding stuff into a URL
There are also many different "escape" function (e.g. inserting into JSON, inserting into mysql, inserting into other databases). Use the right one for what you need - and don't use it for other purposes.
Check the functions for more details.
As it currently stands your code is not safe even with all those efforts - but it's really simple to fix!
try with preg_replace() function and no need of \n\r both you can do with \n or PHP_EOL only
$jawaban = preg_replace('#<br\s*?/?>#i', "\n", $jawaban1);
or
$jawaban = preg_replace('#<br\s*?/?>#i', PHP_EOL, $jawaban1);
you must knowing these before working with strings:
"\n\r" means new line.
'\n\r' doesn't mean new line.
doesn't mean new line. It's just HTML number for HTML Symbols. when you are using it, you mean just show \n\r in your browser. this is answer to your question:
both insert "\r\n" into the text , why is this happening?
so, after knowing that, you understand:
if your $jawaban1 string is
Hello <br> and welcome!
and your code is
$breaks = array("<br />", "<br>", "<br/>");
$jawaban = str_ireplace($breaks, "
", $jawaban1);
It means, $jawaban will be exactly like this:
Hello
and welcome!
without any \n\r and just your browser showing it like this:
Hello \n\r and welcome!
If you want to replace all br by \n\r just use the code in your question:
$breaks = array("<br />", "<br>", "<br/>");
$text = str_ireplace($breaks, "\r\n", $text);
About preg_replace()
When you can use str_ireplace, Don't use preg_replace. str_ireplace is faster.
Don't do it if you don't need it
in your code you did this:
$unsafejawabanfirst = nl2br($jawabannotcut);
and right after that you want to replace br with \n\r. It's like do and undo. I see that you are trying to show it again inside textarea element. so don't replace \n\r with br. the solution? don't change \n\r at all and if you want save it to the db just save it with \r\r. when you need it to show outside of textarea element just use nl2br function.
There is always something that saves my day, it is actually a workaround and your question is a trigger for me to get deeper to this matter - once for all.
For now, here you go - nice & sleek workaround:
There is already nl2br() function that replaces inserts <br> tags before new line characters:
Example (codepad):
<?php
// Won't work
$desc = 'Line one\nline two';
// Should work
$desc2 = "Line one\nline two";
echo nl2br($desc);
echo '<br/>';
echo nl2br($desc2);
?>

How to insert a new line break within the php code

<?php echo nl2br($valueu->getarea($rows['province'].'|'.$rows['city'].'|'.$rows['area'],' ')); ?></td>
how to put a line break in between city and area when outputted to a browser.
Thanks
Use \n. Just add it with the sting like this I."\n" like pie.
You can also use nl2br like this echo nl2br("One line.\nAnother line.");
Try double quote "\n".
If you use single quote '\n', PHP will just interpret as a literal \n, but within double quote, it will parse it as an escape sequence (newline character) and echo it. More about strings here.
echo nl2br('Hello \n world');
// -> Hello \n world
echo nl2br("Hello \n world");
// -> Hello <br /> world
In a browser, you may need to use "<br/>" instead of a newline "\n".
echo($valueu->getarea($rows['province'].'|'.$rows['city'].'<br />'.$rows['area'],' '));
Something like that?

how to print special characters which are a string in variable with php?

I'm making this chat server, but it doesn't work quite well. When you send a piece of text, it first gets encoded by the function base64_encode() and then gets sent to a MySQL database.
Then the receiver gets the text from that same MySQL database, which is of course first decoded by the function base64_decode().
The only problem is with the special characters like \n \' and \t: when I get the data from the database and print it between two textarea tags, I see \n as a string, and not as actual line breaks.
In short, I need to fix this problem:
$String = 'Line 1 \n Line 2';
print '<textarea>' . $String . '</textarea>';
//The result I want
//<textarea> Line 1
//Line 2 </textarea>
The function nl2br doesn't work, because tags inside a textarea tag won't work, and also because there other characters like apostrophes.
Could anybody help me?
Thanks!
You need to enclose your string into double quotes, for special characters to be evaluated.
$String = "Line 1 \n Line 2";
print '<textarea>' . $String . '</textarea>';
If you change this:
$String = 'Line 1 \n Line 2';
print '<textarea>' . $String . '</textarea>';
to this:
$String = "Line 1 \n Line 2"; // double quote
print '<textarea>' . $String . '</textarea>';
... you will get the output you want.
This one is also works same as using " ... ", however maybe helps in your case:
$string = <<<EOT
Line 1 \n Line 2
EOT;
echo '<textarea>' . $string . '</textarea>';
As the others said, your problem is Single-Quotes.

Issues while using Quotes in PHP

I have Learnt that Quotes doesn't matter in PHP.
But in the following code, if I try to use single quotes in eval(); I get error, on the other hand code works fine with Double Quotes.
$a = '2';
$b = '3';
$c = '$a+$b';
echo $c.'<br/>';
eval("\$c = \"$c\";");
//eval('\$c = \'$c\';'); //Parse error: syntax error, unexpected T_VARIABLE, expecting T_STRING
echo $c;
PHP.net says that escape sequences are not expanded when using single quotes.
Quotes do matter ;-)
<?php
$color = "red";
echo "My car is $color"; // Outputs "My car is red"
echo 'My car is $color'; // Outputs "My car is $color"
?>
Unlike double quotes, PHP does not parse variables in single quotes.
Example:
$name = 'John';
echo 'hello $name'; // hello $name
echo "hello $name"; // hello John
More Information
FYI, it isn't good idea to use eval in production environment for security reasons.
Using eval is a bad idea but if you are doing this for learning purpose then the correct way is
eval("\$c = \$c;");
.
don't use eval and update your string-quoting skills here:
The following example was lifted from: The PHP Manual
<?php
echo 'this is a simple string';
echo 'You can also have embedded newlines in
strings this way as it is
okay to do';
// Outputs: Arnold once said: "I'll be back"
echo 'Arnold once said: "I\'ll be back"';
// Outputs: You deleted C:\*.*?
echo 'You deleted C:\\*.*?';
// Outputs: You deleted C:\*.*?
echo 'You deleted C:\*.*?';
// Outputs: This will not expand: \n a newline
echo 'This will not expand: \n a newline';
// Outputs: Variables do not $expand $either
echo 'Variables do not $expand $either';
?>

How to handle newlines in Javascript? (from PHP)

I have code like this:
<?php
echo '<script type="text/javascript">';
echo 'var out="'.$txt.'";';
echo '</script>';
?>
Where $txt is a PHP variable that can contain newlines like this:
line1
line2 hello world
Which would end up like this:
var out="line1
line2 hello world";
Which will cause a Javascript error, of course.
What is the best way to handle this? The out variable will be used in a HTML textarea, so I don't think it can be parsed into <br>
$txt = str_replace( array( "\n", "\r" ), array( "\\n", "\\r" ), $txt );
should replace newlines. Don't do it this way.
This is a naïve implementation of string escaping for JavaScript. As you're actually trying to format a string for use in JavaScript, a much better solution would be to use json_encode:
$txt = json_encode($txt);
echo "<script>var out={$txt};</script>";
json_encode will correctly escape special characters in strings, such as quotes, tabs, form feeds, and other special unicode characters. It will also perform all the correct escaping for converting objects, arrays, numbers, and booleans.
you can add a \ at the end of a line to create a multi line String
var out="line1 \
line2 hello world";
Most of these don't work for me.
Normally, I'd use json_encode like
<?php
$MyVar = json_encode($MyVar);
?>
<javascript language='javascript'>
MyVar = <?php echo $MyVar; ?>
But for a quick fix you can just break a line like this:
Pay attention to the double quotes.
<?php
$MyVar = "line one here
then line two here
finally line five here";
//** OR
$MyVar = $MyVarA .
"
"
. $MyVarB;
?>
<HTML>
<HEAD>
<javascript language='javascript'>
Myvar = "<?php echo $MyVar; ?>";
. . .
You can use str_replace to convert line breaks into a different character (in this case, perhaps a space, but it depends how you want the output to show up)
$out = str_replace("\n", '\n', $in);
$content = str_replace( "\\n", "\\\\\\n", $content );
Result:
var a = "Hello \
World"
I tried this and it worked well.
<?php
echo '<script type="text/javascript">';
$txt = "line1 \\n line2 hello world";
echo 'var out="'.$txt.'";';
echo '</script>';
?>
I am using PHP 5.3

Categories