nl2br to display textarea - php

I am implementing a contact form. When the user submits the form, all input is validated and stored in a session. It is then forwarded to a page that informs the user of a successfully posting of the comment, displaying the data entered.
The trouble I am having is that all new lines are not being displyed correctly as breaks using nl2br().
User input:
<textarea name="comments" rows="10" cols="50" id="comments" tabindex="5" title="comments">
<?php echo isset($_POST['comments']) ? $_POST['comments'] : ''; ?>
when validated...
$_SESSION['comments'] = $_POST['comments'];
forwarded on to contact-sent page and then appended to the string to display
$forwardString = "<h2>New Website Comment: </h2><h3>" . $cEmail . "</h3><p>" . $cComment . "</p>";
Then displayed:
echo nl2br($forwardString);
Where do I implement the nl2br() function?
Example input:
Just a test to verify contact works correctly.
We should see two line breaks here.
One line break here
Currently yields:
Just a test to verify contact works correctly.We should see two line breaks here.One line break here

try
echo nl2br(stripslashes($forwardString));
You could be possibly escaping the string twice so the \n becomes \n

Related

PHP (json_encode, implode) store data in a txt file

I'm trying to store data in a .txt file..
The data is already appear on my HTML page but I couldn't know how to post them in a txt file or store them in a session.
In main page:
<?php
echo implode('<br/>', $res->email);
echo json_encode($res->password);
?>'
I want to do something like below:
<?php
$login = "
EMAIL : $_POST['$res->email'];
PASSWORD: $_POST['$res->password']; ";
$path = "login.txt";
$fp = fopen($path, "a");
fwrite($fp,$login);
fclose($fp);
?>
So this $_POST['$res->email']; doesn't work with me I get in the login.txt:
EMAIL : json_encode(Array)
PASSWORD: implode('<br/>', Array)
Neither function calls nor $_POST['$res->email'] would work in string/interpolation context.
While unversed, you should assemble your text data line by line:
$login = " EMAIL : "; # string literal
$login .= implode('<br/>', $res->email); # append function/expression result
$login .= CRLF; # linebreak
$login .= " PASSWORD: "; # string literal
$login .= json_encode($res->password); # append function/expression result
$login .= CRLF; # linebreak
And instead of the oldschool fopen/fwrite, just use file_put_contents with FILE_APPEND flag.
When you use post data you recieve it in your php file. You dont send post data from a php file. With that in mind you manipulate this data with php in the following way:
If is data you recieved from post:
echo $_POST['field'];
This will show the message stored on the field variable among the posted data. But check that the field will be always a string (even though the contents may not be so)
If you want to acces dynamically a field just have in mind that it should be a string for example:
$email = "example#gmail.com";
echo $_POST[$email]
This will NOT return the posted email, but will return the contents from a variable inside Post called "example#gmail.com". Which is the same as :
echo $_POST["example#gmail.com"];
But making now a correct example. if you have this html in your webpage
<form action="/yourphp.php" method="post" target="_blank">
<input type="text" name="email">
<input type="submit" value="Submit">
</form>
you will be able to recover the data from the input field named "email"
echo $_POST['email'];
and this will return the email inside the input.
After you have this clear, you can manipulate the data in different ways to send them to a file, but usually you will have to instantiate a handler, open a file, write content, save and close the file, all depending on your handler.

Session variable in hidden field not being passed to $_POST on submit

I've have this bit in my processor.php file...
session_start();
$_SESSION['address'] = $_POST['field_2'];
$_SESSION['name'] = $_POST['field_1'];
Those variables are being passed to another page and pre-filling inputs on a second form like this...
<input type="hidden" name="Name" value="<?php echo $_SESSION['name']?>">
<input name="Address" type="text" value="<?php echo $_SESSION['address']?>">
Then that form is being submitted to email...
mail($to, $subject,"Form data:
Name: " . $_POST['Name'] . "
Property Address: " . $_POST['Address'] . "
More Fields ", $headers
);
The email comes through successfully with the pre-filled "Property Address" but "Name" is blank. Why is the hidden input not passing the variable for $_POST['Name']?
While it seemed like the hidden field was the problem, it was not. Every thing was working except for the second line here.
mail($to, $subject,"Form data:
Name: " . $_POST['Name'] . "
Email: " . $_POST['Email'] . "
Property Address: " . $_POST['Address'] . "
Lots More Fields ", $headers);
The whole `mail()' function bit was a copy-and-paste snip-it from the web into Sublime Text. The syntax was perfect, but I eventually found that there was an invisible non-ASCII character in the Name line left over from the copy paste from web snip-it operation. I checked if anyone else ever had a similar problem like this and immediately found this FileUtils.mv throwing Invalid char \302 and \255 exception
The moral of the story is that saving time by using snipits may not always save you time. I should have enabled "draw_white_space" in Sublime Text and I would have probably caught it a lot sooner.
As Fred -ii- pointed out the message body arguments all would have been better concatenated as a $message variable. Whose advice I've now followed.
At step 2, check in the generated HTML code if the "value" attribute have the correct value.
Also, instead of using at step 3 $_POST['Name'] , use $_REQUEST['Name']. With this, it will work if POST or GET request.

Form to CSV and "Thanks" in new tab using POST

I'm trying to accept a form and write it to a CSV (invisible to the people submitting the form, but I can look at it as a compilation of everyone's entries on the server when I feel like it). Every time someone enters the form, it will become a new line on the CSV. To show that the people are actually submitting, a new tab will pop up with a little "thank you" like message and their submission so they can make sure it's theirs. Yes, I do have a JS form validation that works perfectly, but since that doesn't have a problem I left it out to save space.
Here is my current problem. In Firefox, I just get a blank new tab and nothing changes on my--blank--CSV, which is titled testForm.csv. In Chrome, a new tab opens that contains all the code on my php document, and my CSV stays blank.
Here's the snippet of my HTML:
<html>
<body>
<form name="Involved" method="post" action="postest.php" target="_blank" onsubmit="return validateForm();">
Name: <br><input type="text" name="name" title="Your full name" style="color:#000" placeholder="Enter full name"/>
<br><br>
Email: <br><input type="text" name="email" title="Your email address" style="color:#000" placeholder="Enter email address"/>
<br><br>
How you can help: <br><textarea cols="18" rows="3" name="help" title="Service you want to provide" style="color:#000" placeholder="Please let us know of any ways you may be of assistance"></textarea>
<br><br>
<input type="submit" value="Submit" id=submitbox"/>
</form>
</body>
<html>
Here is postest.php:
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$help = $_POST['help'];
$csvData = $name . "," . $email . "," . $help . '\n';
echo "Thank you for your submission! We'll get back to you as soon as we can!";
echo "I'm " . $name . ", my email is " . $email . ", and I can help in that: \n" . $help;
$filepointer = fopen('testForm.csv','a');
if ($filepointer){
fwrite($filepointer,$csvData);
fclose($filepointer);
exit();
}
?>
I checked out this question about echoing to see if that was my problem. I asked this question before and nobody seemed to find anything wrong with my code other than the obvious $_POSTEST problem. This page looked like what I was going for, but wasn't. This question kind of had what I was going for but didn't actually have the POST code and the answer was one of the most useless things I've ever read (in a nutshell: "Just do it. It isn't that complicated." and some links to other SO questions, which I followed). They brought me here and here. I put exit(); after fclose() like it seemed to work for the first one (it did nothing). With the second, the user's code was too far removed from the codes I've been looking at for me to change my code over to what he/she was doing. I've been searching a lot, and doing extensive googling, but I'm going to cut my list of research here because nobody wants to read everything; this is just to prove I tried.
Let me know if there's anything else you need; I am a complete php novice and it's probably something very basic that I missed. On the other hand, I'm not seeing any major differences between my code and others' at this point.
Try something like this :
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$help = $_POST['help'];
$filepointer = fopen('testForm.csv','a');
fputcsv($filepointer, array($name,$email, $help));
echo "Thank you for your submission! We'll get back to you as soon as we can!";
echo "I'm " . $name . ", my email is " . $email . ", and I can help in that: \n" . $help;
?>
This is the error :-
---> $filepointer = fopen('testForm.csv','a');
$fp = fopen('testForm.csv','a');
if ($fp){
fwrite($fp,$csvData);
fclose($fp);
exit();
}
And the real issue is developing without
display_errors = On
log_errors = On
Look for these parameters in the php.ini file, and turn them on, unless you are developing on a live server, in which case, you really should set up a test environment.
and then not looking at the php error log
UPDATE
There was only one line to change actually, here is the complete code.
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$help = $_POST['help'];
$csvData = $name . "," . $email . "," . $help . '\n';
echo 'Thank you for your submission! We\'ll get back to you as soon as we can!';
echo '\"I\'m \"' . $name . ", my email is " . $email . ", and I can help in that: \n" . $help;
$fp = fopen('testForm.csv','a'); // only line changed
if ($fp){
fwrite($fp,$csvData);
fclose($fp);
exit();
}
?>
Your error is really basic and I am ashamed of you. Your problem is obviously that you have not been using a server, nor do you have a PHP package installed on your computer. When you told your computer target="_blank" and method="post", it knew what you wanted, being HTML. However, not having anything that parsed PHP, it had no idea how to read your code and came up as a blank page in Firefox and a block of code in Chrome.
You, indeed, have no idea what you are doing.

Keeping carriage returns in SQL for HTML display without additional markup?

I am writing an application where a user enters text into a textbox inside a form and the text is stored in a SQL db inside a MEDIUMTEXT field. I am testing right now so the table only has 2 field "1" for the index and "2" for the stored text.
<form method="post" action="index.php" enctype="multipart/form-data" >
<h3>Input Text Here</h3>
<textarea name="text" cols="40" rows="6" ></textarea><br/>
<input type="submit" value="Submit" />
</form>
The stored text then is retrieved in another page and displayed.
<?php
$query = "SELECT * FROM test_table WHERE 1='1'";
$result = mysql_query($query);
if (!$result) die ("Database access failed: " . mysql_error());
$results = mysql_fetch_array($result, MYSQL_ASSOC);
echo $results['2'];
if(isset($_POST['text'])) {
echo printText($_POST['text']);
function printText($txt) {
if(!empty($txt)) {
return $txt;
} else {
return 'You didn\'t write anything.';
}
}
}
?>
The problem is that when the text is displayed all the carriage returns disappear and multiple paragraphs become one.
Can anybody guide me in the appropriate direction? Should I be using regular expressions looking for carriage returns and marking them up? Is there a less search intense method? I tried nl2br(), but I guess you need actual \n entries for it to work.
I am writing this for someone to easily update a "news blub" on their landing page without having to use a text editor and writing code.
Thanks!
I tried nl2br(), but I guess you need actual \n entries for it to
work.
nl2br is the function you need. From the manual:
Returns string with '<br />' or '<br>' inserted before all newlines
(\r\n, \n\r, \n and \r).
If a user submits data with carriage returns then you will be getting "actual" \n entries (or one of the others mentioned in the manual description). Ensure you are calling it whenever you are echoing the pertinent text.

How to save Textarea input after convert line breaks as BR in SQL

I use ckeditor in admin panel but in user submit form use simple textbox so user can input text and submit. Problem is when user enter text in textarea with Line Breaks it saves as it in SQL. I want to add BR after each line in sql.
For Example User Submits:
![F.R.I.E.N.D.S.:
(F)ight for you.
(R)espect you.
(I)nvolve you.
(E)ncourage you.
(N)eed you.
(D)eserve you and
(S)tand by you.][1]![SCREENSHOT oF DB SAVE][2]
got saved in DB as it with next line showing in output. But I want to save in DB as:
F.R.I.E.N.D.S.:<br />
(F)ight for you.<br />
(R)espect you.<br />
(I)nvolve you.<br />
(E)ncourage you.<br />
(N)eed you.<br />
(D)eserve you and<br />
(S)tand by you.
I use nl2br but its not working on user submit form If I use nl2br on admin processing form then on those fields already added with ckeditor it adds two BR tags.
Code used on user submit form is:
<textarea name="content" id="content" cols="60" rows="10" class="span7"><?php if(isset($content)) { echo $content; } ?></textarea>
$content = trim($_POST["content"])
$content = mysql_real_escape_string($content);
$content = nl2br($content);
No processing is used on admin approval form where ckeditor used on textarea. Text output from DB appears without Line Breaks in a single line in ckeditor.
if I use nl2br while output on this form it works but adds double BRs on earlier text posted through ckeditor.
also tried $content = preg_replace("/\r\n|\r/", "<br />", $content); as suggested by some one on stackoverflow on similar question
pls suggest me some function for this problem.
also suggest If I need to use some function like htmlentities or stripslashes to process content before Inserting into SQL.
Just replace the new line \r\n, \r first, then trim it.
$content = preg_replace("/\r\n|\r/", "<br />", $_POST["content"]);
$content = trim($content])
Or:
$content = nl2br($_POST["content"]);
$content = trim($content)
Good luck.
You need to use nl2br for displaying the value, whenever you need it, not for saving it.

Categories