I have read all answers related to this but couldn't get the exact order to sanitize data
I have to input
<?php echo 'yes'; ?>
<?php echo 'yes' ?>
into a text area and submit it in database as it is with line breaks and output the code as it is with line breaks just as stackoverflow is doing.
output comes like this
<?php echo \'yes\'; ?>\r\n\r\n<?php echo \'yes\'; ?>
note : htmlspecialchars() is outputting the exact code but without line breaks ...
nl2br() is not taking /r and /n as line breaks
you can also use the below functions when inserting data
$unwanted = array("-", "_", "+"," ", etc .. );
$yourVariable = str_replace($unwanted, "NULL", $yourVariable);
or
trim($yourVariable);
This function returns a string with whitespace stripped from the beginning and end or yourVariable
Related
I am adding a pad to my string, to fill with spaces, but it doesn't work
the code is here
<?php
$string1 = "Product 1 ";
$newString = str_pad($string1,100);
echo $newString."test";
echo "<br>";
$string2 = "Product 2222 ";
echo str_pad($string2,100," ")."test";
echo "<br>";
?>
the output is like this:
Product 1 test
Product 2222 test
You could try $str = str_pad($string2,(100*strlen(" "))," ")."test"; instead.
renders to a non-breaking-space in html (and when writing to document with fpdf).
Please note this can only work with fpdf when you tell it to write all lines as html! And the encoding should be utf-8 probably
$fpdf->Write(iconv('UTF-8', 'windows-1252', html_entity_decode($str)));
When the output of the PHP is converted to HTML, all the white spaces except the first are removed and it is the default feature of HTML and web browsers. so the output will not be correct.
You have to use the " " instead of white space in the str_pad function. HTML don't ignore the " " and against each existance of it, HTML adds a white space to the string.
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);
?>
I have descriptions stored in mySQL with line breaks, so when I output them as they should be, I use:
<?
echo nl2br($description);
?>
And it shows:
Line 1
Line 2
Line 3
So far, so good. Now, I want to use that same description for the meta tags and the problem is that even if I output them like:
$old_string = nl2br($description);
$new_string = preg_replace("/<br \/>/"," ",$old_string);
echo $new_string;
I still get these meta tags:
<meta property="og:description" content="Line 1
Line 2
Line 3"/>
How do I make it output all in 1 line, with just a space in between them?
Thank you very much for any help :)
Don't use nl2br for META, but simply replace line-breaks on the string from database. Note that depending on your environment, a linebreak can be represented with \r\n or simply with \n. So try to use the following code:
$onelinestring = str_replace("\r\n", " ", $description);
$onelinestring = str_replace("\n", " ", $onelinestring);
Try:
$singleLine = str_replace("\n", " ", $string);
Without nl2br, just the string fetched from the db.
I'm using textarea to get data that I insert into a database.
I'm using htmlspecialchars() to get rid of the single quotes and double quotes but it doesn't convert new lines into something so I'm left with a very long piece of code that doesn't have new lines and looks messy.
I've checked the manual but I can't find how to convert it.
How would I do this?
EDIT:
My intended output is the same as what the user inputted.
So if they inputted into the textarea...
Hi
This is another line
This is another line
It would store into the database like...
Hi\r\nThis is another line\r\n This is another line.
or something like that.
Then when I echo it again then it should be fine.
Anthony,
If you are referring to when you get it back out and you want it to look nice, and you aren't putting it back into a textarea, you can use the mythical function nl2br() to convert new line characters into HTML characters.
$data = 'Testing\r\nThis\r\nagain!\r\n';
echo nl2br($data);
This results in:
Testing
This
again!
I believe what you are looking for is
nl2br($string);
That will convert the returns to <br> tags
I will also give you this script that has worked well for me in the past when nl2br does not.
$remove = array("\r\n", "\n", "\r", "chr(13)", "\t", "\0", "\x0B");
$string = str_replace($order, "<br />", $string);
It should be:
<?php
addslashes( strip_tags( nl2br( $data ) ) );
?>
addslashes : will escape quotes to prevent sql injection
strip_tags : will remove any html tags if any
nl2br : will convert newline into <br />
My code works as follows:
Text comes to server (from textarea)
Text is ran through trim() then nl2br
But what is happening is it is adding a <br> but not removing the new line so
"
something"
becomes
"<br>
something"
which adds a double new line. Please help this error is ruining all formatting, I can give more code on request.
Creation of post:
Shortened creation method (Only showing relevent bits) Creation method:
BlogPost::Create(ParseStr($_POST['Content']));
ParseStr runs:
return nl2br(trim($Str));
Viewing of post:
echo "<span id='Content'>".BlogPosts::ParseBB(trim($StoredPost->Content))."</span>";
ParseBB runs:
$AllowedTags = array(
// i => Tag, Tag Replacement, Closing tag
0 => array("code","pre class='prettyprint'",true),
1 => array("center","span style='text-align:center;'",true),
2 => array("left","span style='text-align:right;'",true),
3 => array("right","span style='text-align:left;'",true)
);
$AllowedTagsStr = "<p><a><br><br/><b><i><u><img><h1><h2><h3><pre><hr><iframe><code><ul><li>";
$ParsedStr = $Str;
foreach($AllowedTags as $Tag)
{
$ParsedStr = str_replace("<".$Tag[0].">","<".$Tag[1].">",$ParsedStr);
if($Tag[2])
$ParsedStr = str_replace("</".$Tag[0].">","</".$Tag[1].">",$ParsedStr);
}
return strip_tags($ParsedStr,$AllowedTagsStr);
Example:
What I see:
What is shown:
It's because nl2br() doesn't remove new lines at all.
Returns string with <br /> or <br> inserted before all newlines (\r\n, \n\r, \n and \r).
Use str_replace instead:
$string = str_replace(array("\r\n", "\r", "\n"), "<br />", $string);
Aren't you using UTF-8 charset? If you are using multibyte character set (ie UTF-8), trim will not work well. You must use multibyte functions. Try something like this one: http://www.php.net/manual/en/ref.mbstring.php#102141
Inside <pre> you should not need to call nl2br function to display break lines.
Check if you really want to call nl2br when you are creating post. You probably need it only on displaying it.