PHP nl2br posting duplicate <br/>'s? - php

I'm using the following code to post the content of a text box to an HTML file. When the info is submitted, I want there to be <br/> inserted where line-breaks are. I thought using this code would fix the problem:
$content = nl2br($_POST['content']);
But it seems to produce the following if there is already a <br /> in place:
Lorum ipsum.<br /><br />
How do I remedy this?
The post code:
<?php
$fn = "people.html";
if (isset($_POST['content']))
{
$content = stripslashes('content');
$content = nl2br($_POST['content']);
$fp = fopen($fn,"w") or die ("Error opening file in write mode!");
fputs($fp,$content);
fclose($fp) or die ("Error closing file!");
}
?>
How it's being submitted:
<form action="<?php echo $_SERVER["PHP_SELF"] ?>" method="post">
<textarea rows="25" cols="40" name="content"><?php readfile($fn); ?></textarea>
<input type="submit" value="Sauver">
</form>

From what I understand, if the html your inserting already contains a <br /> tag then it adds two because of the \n after the <br />, to remedy this you would need to strip the extra break tag from the input using str_replace or regex.
Then when echoing result back to the textarea you should use: <?=htmlentities(file_get_contents($fn))?> as SpoonNZ suggested.
note: using user submitted html without passing through htmlentities or $_SERVER["PHP_SELF"] within a form will open you upto XSS

You should not be storing your line breaks as <br> in your persistent storage (your text file). In your text file, line breaks should be stored as line breaks ("\n"). You should only transform them into HTML <br> tags when you output them into HTML. You also need to escape any user supplied content you put into HTML (for why, read The Great Escapism).
if (!empty($_POST['content'])) {
file_put_contents('people.txt', $_POST['content']);
}
Then:
<textarea rows="25" cols="40" name="content"><?php
echo nl2br(htmlspecialchars(file_get_contents('people.txt')));
?></textarea>
This way line breaks are line breaks at all times, they just need to be converted to <br>s because that's the only way to conserve them in an HTML context.
As for why line breaks are doubling, there simply seems to be an additional line break added at some point, possibly by the browser when the textarea content is submitted. You may want to trim your input/output to avoid any leading or trailing whitespace.

//$content = stripslashes('content');
$content = preg_replace('~\s*<br ?/?>\s*~',"<br />",$_POST['content']);
$content = nl2br($content);
Something like that should strip excess whitespace around line breaks for you.
Also, why are you using stripslashes? That should only be necessary if you have magic quotes on, and you shouldn't have magic quotes on. You also have got that line's syntax wrong anyway.
edit: Still trying to interpret what you're saying. I'm thinking this might help:
<form action="<?php echo $_SERVER["PHP_SELF"] ?>" method="post">
<textarea rows="25" cols="40" name="content"><?htmlentities(preg_replace('~\s*<br ?/?>\s*~i',"\n",(file_get_content($fn))); ?></textarea>
<input type="submit" value="Sauver">
</form>'
Will start with the correct data. Perhaps.

Related

PHP write to text file is making text drop one line every time update

I am working on a very basic client/case management tool. Part of this involved text boxes which use PHP to read/write text to .txt files.
The problem I am having is that every time you click "submit" the text drops down one line. When you first write some text in the text box, you obviously write it on the top line, but when you click submit it drops down one line in the text box. The odd thing is that the first time this happens (so the text shows one line down), the .txt file shows the text actually on line one as it should be (although it shows on line 2 in the text box). However, if you click submit again (for example if adding/changing info in the text box, or even just clicking submit on its own) the text drops down another line in the text box, which does make it drop down a line in the .txt file.
Am I missing something? Is there any way to stop this happening?
This is the code I am using on the page that shows the text box:
<form action=".write-case-notes.php" method='post'>
<textarea name='textblock' style="width: 490px; height: 170px; resize:
none;" >
<?php echo file_get_contents( ".case-notes.txt" ); ?>
</textarea>
<input type='submit' value='Update Case Notes'>
</form>
This is the php code that I am using to write to the .txt file:
<?php
$f = fopen(".case-notes.txt", "w");
fwrite($f, $_POST["textblock"]);
$newURL = '.parties.php';
header('Location: '.$newURL);
?>
The $newURL section of the above code is to make the page return to the page with text boxes after new text has been submitted.
You actually have the blank lines in your own code:
<form action=".write-case-notes.php" method='post'>
<textarea name='textblock' style="width: 490px; height: 170px; resize: none;" >
<?php echo file_get_contents( ".case-notes.txt" ); ?>
</textarea>
<input type='submit' value='Update Case Notes'>
</form>
So when the HTML is rendered, you...
First, open your <textarea ...> tag.
Then write a blank line inside the textarea.
Then dump the file contents.
You actually dump another blank line after it.
Then you close the textarea tag.
Solution 1 (quick & dirty)
Eliminate the blank lines and blank spaces and new lines from your HTML like this:
<form action=".write-case-notes.php" method='post'>
<textarea name='textblock' style="width: 490px; height: 170px; resize: none;" ><?php echo file_get_contents( ".case-notes.txt" ); ?></textarea>
<input type='submit' value='Update Case Notes'>
</form>
Solution 2 (a bit more clean-code)
If you want a bit more of clean code:
Assign your content into a variable.
If you do not use a templating engine like smarty, twig or whatever, template your self with simple PHP substitutions.
<?php
// Content to be substituted.
$textAreaContent = file_get_contents( '.case-notes.txt' );
$textAreaStyle = 'width: 490px; height: 170px; resize: none;';
// Template to substitute in.
$template =
'<form action=".write-case-notes.php" method="post">
<textarea name="textblock" style="%s">%s</textarea>
<input type="submit" value="Update Case Notes">
</form>';
// Render
$html = sprintf( $template, $textAreaStyle, $textAreaContent );
echo( $html );
Notes:
I changed the single quotes in yout HTML into double quotes.
If you open the <?php tag and never close it, you are 100% sure you are not sending unwanted line terminators or spaces. This is documented here: http://php.net/manual/en/language.basic-syntax.phptags.php
The documentation says:
If a file is pure PHP code, it is preferable to omit the PHP closing
tag at the end of the file. This prevents accidental whitespace or new
lines being added after the PHP closing tag, which may cause unwanted
effects because PHP will start output buffering when there is no
intention from the programmer to send any output at that point in the
script.
Being in 2018, seriously consider using a templating engine. These links can help:
Twig - http://twig.sensiolabs.org/
Smarty - https://www.smarty.net/
Any other from this article: http://acmeextension.com/best-templating-engine/
Hope to help!
You could try doing the following:
$file = './case-notes.txt';
$f = fopen($file, 'a');
fwrite($f, isset($_POST['textblock'])."\n");
fclose($f);
header('Location: ./parties.php');
EDIT: made the Location redirect simpler.
Edit: new solution below
<form action="./write-case-notes.php" method='post'>
<textarea name='textblock' style="width: 490px; height: 170px; resize:
none;" >
</textarea>
<input type='submit' value='Update Case Notes'>
</form>
<?php
if (isset($_POST['textblock'])) {
$text_block = $_POST['textblock'];
$file = './case-notes.txt';
$f = fopen($file, 'a');
fwrite($f, $text_block."\r\n");
fclose($f);
}
?>
<br /><br /><br />
<?php $output = file_get_contents( "./case-notes.txt" );
print $output."<br />"; ?>

How to insert an active link to an input textbox?

Is it possible to insert an active link to an input textbox?
I tried using an <a> tag inside the value of html but its not working.
<?php $email = "example#link.com "; ?>
<input type="text" id="email" name="email" value="<?php echo $email; ?>">
It only returns the text without the hyperlink value.
A couple things are wrong here...
You're not escaping your quotes. Therefore the PHP is invalid.
You're trying to put HTML inside a attribute, which is also invalid.
The only alternative I could see being used here is an HTML element with contenteditable="true" applied. This makes it so an element (per say a <div>) can have it's content be modified.
<?php $email = "example#link.com "; ?>
<div id="fake-email" contenteditable="true"><?php echo $email; ?></div>
Then see this related question if you're doing a form.
Edit:
If you're trying to do a form, then this is one example:
document.getElementById("form").onsubmit = function(){
document.getElementById("email").value =
document.getElementById("fake-email").innerText || document.getElementById("fake-email").textContent;
}
While your form is:
<form action="..." method="..." id="form">
<div id="fake-email" contenteditable="true"></div>
<input type="hidden" id="email" name="email" />
</form>
No, it isn't possible. Input values will always be rendered as plain text. If the user doesn't need to edit the link I would just put it beside the input.
Otherwise you might want to look into WYSIWYG Editors. Links to two of the most popular below.
TinyMCE
CKEditor
You need to escape quotes when including it in your php variable.
<?php $email = "example#link.com "; ?>
You need to use a backslash when you're using double quotes.
Alternatively, you can write it as such:
<?php $email = 'example#link.com '; ?>
If you start with single quotes, then you don't need to escape the double quotes. \
I strongly suggest you read up on escaping characters when need be.

How to send text area content to next page via post method?

I got a textarea that has some html code in it. I want to send the content of this textarea without any change to next page via post method.
<html>
<form id="myform" name="myform" action="./getdata.php" method="post">
<td><textarea rows="7" cols="15" name="outputtext" style="width: 99%;"></textarea></td>
<input type="submit">
</form>
</html>
and my php code :
<?
$file_contents = $_POST['outputtext'];
?>
<textarea rows="30" cols="150"><?PHP print_r($file_contents); ?></textarea>
The problem with my code is that the orginal content of my first textarea gets changed when it sends to next page! For example:
<a href="/season/episodes.php?name=ok&id=1">
becomes:
<a href=\"/season/episodes.php?name=ok&id=1\">
could you guys how i can preserve the original html content without it changes in next page ?(Note all my html content changes in second pages which i dont want to change).My second textarea in second page is for testing purpose and i actually want to parse orginal value of $file_contents but for some reason it changes!
In your second PHP script, simply use strip_slashes to remove the extra slashes in the passed text:
<?
$file_contents = stripslashes($_POST['outputtext']);
?>
<textarea rows="30" cols="150"><?PHP print_r($file_contents); ?></textarea>

How to insert a newline by pressed enter key into a database in PHP? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to save user-entered line breaks from a TEXTAREA to a database?
When I press an ENTER KEY in a textarea it goes to newline. But when I receive this value from action page it converts to a white space. I want to receive ENTER KEY character as a newline from action page as not a white space.
Sample code : this is the HTML code
<form action="go.php" method="POST">
<textarea name="aa" cols="10" rows="10"></textarea>
<form>
Her is the go.php code :
<?php
$txt=$_POST['aa'];
echo $txt;
?>
If I input like
"this is me(PRESS ENTER KEY)this is he(PRESS ENTER KEY)".
I want to the output as like
"this is me(newline)this is he(newline)".
But I am getting from go.php like
"this is me this is he".
Here is no any newline but white space.
Please anyone help me. Why it is happen.
I believe you want nl2br. This will insert HTML line breaks before all newlines in a string. If you are planning to store this in a database, you'll need something similar to mysql_real_escape_string() to escape the line breaks.
<?php
echo nl2br("foo isn't\n bar");
?>
The HTML would look like:
foo isn't<br />
bar
Your code would then look like:
<?php
$txt=$_POST['aa'];
echo nl2br($txt);
?>
You need to use nl2br function to capture and replace newline. Working code below;
<form action="go.php" method="POST">
<textarea name="aa" cols="10" rows="10"></textarea>
<input type="submit" value="s">
</form>
Here is the go.php code :
<?php
$txt=$_POST['aa'];
echo nl2br($txt);
?>

<br /> tags appearing in textarea output

I have an input form with two textareas allowing a user to type in words separated by commas in each.
<form action="http://www.example.com/output.php" method="post">
<table border="0">
<tr>
<td>
<h3 class="title">Prefix</h3>
<textarea cols="34" rows="8" name="cat[]"></textarea></td>
<td>
<h3 class="title">Suffix</h3>
<textarea cols="34" rows="8" name="cat[]"></textarea></td>
</tr>
</table>
Enter words separated by a comma.
<input type="submit" value="Go" /> </form>
It then passes these to the output form which explodes the words from the commas and then concatenates them together until all possible permutations of the words are created. It then prints out the results into a textarea. My problem is that the output (whilst correctly formatted and have the linebreaks in between each permutation) has a br tag at the end of each line. Eg.
testtest2<br />
testtest2<br />
testtest4<br />
testetest2<br />
testetest2<br />
testetest4<br />
Output form:
$cat = $_POST['cat']; //trait set for textbox inputs
foreach(array_keys($cat) as $key){
$cat[$key] = explode(",", str_replace(' ','',$cat[$key]));
}
function showCombinations($string, $traits, $i)
{
if ($i >= count($traits))
echo trim($string)."\n";
else
{
foreach ($traits[$i] as $trait)
showCombinations("$string$trait", $traits, $i + 1);
}
}
?>
<form name=form1 method=post action=''''>
<textarea><?php ShowCombinations('', $cat, 0); ?></textarea>
</form>
When I remove the textarea tags for the output it works fine.
When I leave the textarea tags and remove/replace echo trim($string)."\n"; with "\r" or 'n' or "\n\r", the disappears but I also lose the linebreak
Replace echo trim($string)."\n"; with echo nl2br($string); then same result as 2.
Replace with echo nl2br($string)."\n"; then same result as 1.
Would appreciate any help. My noob brain is about to implode.
I'll preface this by saying I use Blogger not Wordpress but I imagine there are similarities. In Blogger there is a setting to convert line breaks into <br> tags. I guess it's convenient if you're not putting code snippets and the like in (if you're blogging about cats or something) but not so much for programming. I had to turn it off and put in my paragraph tags, etc manually.
Here is one less than ideal solution, which also mentions the issue of Wordpress inserting <br> tags in forms.
I think the <br /> tag is what you want in this case. Newline characters like \n and \r don't do anything in HTML - all whitespace, including newlines, is ignored. The <br /> tag is essentially the HTML equivalent - it stands for "break". I don't know too much about PHP specifically, so I don't know why it's putting the <br /> there for you automatically, but that's the correct HTML for what you're describing.
Technically, there are better ways to format your output then using those tags, but that's more of an advanced topic. If you are a bit new to this, like you said, then just get it working this way for now, and then maybe sometime down the road you can learn about proper semantic HTML markup, CSS styling, etc.
Try using this, I already test it...
<!DOCTYPE HTML>
<html>
<head></head>
<body>
<?php
if(isset($_POST['status'])){
$newLineCode = "<br/>";
$message = $_POST['status'] ;
$modifiedTextAreaText = ereg_replace( "\n", $newLineCode, $message);
echo " <p>Result of Code Snippet:</p> " . $modifiedTextAreaText ;
}
?>
<form action="" method="post">
<textarea name="status"></textarea>
<input type="submit"/>
</form>
</body>
</html>
why not display the results on a <div> perhaps or a <p> ??
I believe \n should work. Perhaps you do not have or have an incorrect doctype.
Example: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
If all else, I like lock's answer. You could us a <div> and you could even style it to look similar to a <textarea> (or even better!)
It took some looking, but after some time I was able to pinpoint these two locations (lines 154 & 165 - WP 2.8) in the wp-includes/formatting.php file.
154 $pee .= '<p>' . trim($tinkle, "\n") . "</p>\n"; //<-- before
154 $pee .= trim($tinkle, "\n") . "\n"; //<-- after
165 $pee = preg_replace('|(?<!<br />)\s*\n|', "<br />\n", $pee); // optionally make line breaks <-- before
165 $pee = preg_replace('|(?<!<br />)\s*\n|', "\n", $pee); // optionally make line breaks <-- after
This took care of the paragraph and and break tags in my textarea field.
I solved my problem by using strip_tags function. when user would edit the past post, it was saving in the database and displaying on the blog. But strip_tags function took care of it.

Categories