PHP textarea into database - php

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

Related

How to remove tags from data in the database?

So I have inserted data in the database that contains \n and \t. How can I display on the webpage with PHP without \n and \t appearing on the data to be displayed?
use preg_split
$output = preg_split( "/ (/n|/t) /", $input );
use explode
if consider your answer from db is
$input="hai /n hello /t";
$output1=explode('/n',$input);
$output=explode('/t',$output1);
it's working if result within foreach you may add this line into foreach()
item = item.replace(/<(.|\n)*?>/g, '');

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

Passing string to a Javascript function does not work

I am trying to pass a string to a javascript function which opens that string in an editable text area. If the string does not contain a new line character, it is passed successfully. But when there is a new line character it fails.
My code in PHP looks like
$show_txt = sprintf("showEditTextarea('%s')", $test_string);
$output[] = '<a href="#" id="link-'.$data['test'].'" onclick="'.$show_txt.';return false;">';
And the javascript function looks like -
$output[] = '<script type="text/javascript">
var showEditTextarea = function(test_string) {
alert(test_string);
}
</script>';
The string that was successfully passed was "This is a test" and it failed for "This is a first test
This is a second test"
Javascript does not allow newline characters in strings. You need to replace them by \n before the sprintf() call.
You are getting this error because there is nothing escaping your javascript variables... json_encode is useful here. addslashes will also have to be used in the context to escape the double quotes.
$show_txt = sprintf("showEditTextarea(%s)", json_encode($test_string));
$output[] = '<a href="#" id="link-'.$data['test'].'" onclick="'.htmlspecialchars($show_txt).';return false;">';
Why don't you try replacing all spaces in the php string with \r\n before you pass it to the JavaScript function? See if that works.
If that does not work then try this:
str_replace($test, "\n", "\n");
Replacing with two \ may work as it will encapsulate.
I would avoid storing HTML or JS in PHP variables as much as possible, but if you do need to store the HTML in a PHP variable then you will need to escape the new line characters.
try
$test_string = str_replace("\n", "\\\n", $test_string);
Be sure to use double quotes in the str_replace otherwise the \n will be interpreted as literally \n instead of a new line character.
Try this code, that deletes new lines:
$show_txt = sprintf("showEditTextarea('%s')", str_replace(PHP_EOL, '', $test_string));
Or replaces with: \n.
$show_txt = sprintf("showEditTextarea('%s')", str_replace(PHP_EOL, '\n', $test_string));

Problems with newlines (nl2br)

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.

nl2br() creates an extra new line

I am trying to insert a description text field into the database.
I was previously just doing something like this:
$group_description = mysql_real_escape_string($_POST['group_description']);
But it was creating problems because when I was taking things out of the database, they were being displayed with \n\r strings instead of new lines.
Here is an example of a page with that problem:
http://www.comehike.com/hikes/hiking_group.php?hiking_group_id=48
So I tried to fix it by adding nl2br like this:
$group_description = mysql_real_escape_string(nl2br($_POST['group_description']));
But that just inserted an extra line :( Here is the example of the current problem:
http://www.comehike.com/hikes/hiking_group.php?hiking_group_id=50
Here is an example of an insert statement I use:
$insert_group_sql = 'INSERT INTO hiking_groups( title , group_description ) VALUES ( "'.$group_name.'" , "'.$group_description.'" ) ';
What is the proper way to do this?
Here is the code I use to display the $group_description
//Convert all urls to links
$group_description = preg_replace('#([\s|^])(www)#i', '$1http://$2', $group_description);
$pattern = '#((http|https|ftp|telnet|news|gopher|file|wais):\/\/[^\s]+)#i';
$replacement = '$1';
$group_description = preg_replace($pattern, $replacement, $group_description);
$group_description = str_replace("\'" , "'", $group_description );
$group_description = nl2br($group_description);
/* Convert all E-mail matches to appropriate HTML links */
$pattern = '#([0-9a-z]([-_.]?[0-9a-z])*#[0-9a-z]([-.]?[0-9a-z])*\\.';
$pattern .= '[a-wyz][a-z](fo|g|l|m|mes|o|op|pa|ro|seum|t|u|v|z)?)#i';
$replacement = '\\1';
$group_description = preg_replace($pattern, $replacement, $group_description);
First, I suggest that you do as Spudley suggests, keep it in the original form in the database and format it once you display it.
nl2br() should work, so I suggest that you check the input data to see exactly what is being input (which is easier to do if you don't format it before you store it in the DB). What it do is it takes \n, \n\r, \r\n and \r and inserts a <br/> instead. You should check that for instance there is no space in between \n and \r.
Also, make sure that you only use nl2br() in one place, since it doesn't replace the new lines, it just inserts the <br/> (that is, if you do nl2br(nl2br($group_description)) you will get two <br/>)
Update:
I see in the additional code that when you display the description, you already have a nl2br(). You need to remove one of them, so that you only add the <br/>s once.
Also, instead of this:
$group_description = str_replace("\'" , "'", $group_description );
$group_description = nl2br($group_description);
Try this:
$group_description = stripslashes($group_description);
$group_description = nl2br($group_description);
That should remove all the sanitizing that mysql_real_escape_string() did, which should solve the problem of the \n\r showing in the text.
Try trim before passing to nl2br:
nl2br( trim($_POST['group_description']) )

Categories