I have a feedback form that saves to a txt file, it saves perfectly but it saves on one line. So multiple comments would be saved on one line so that saves to just one line on notepad rather than separating different comments onto different lines.
Here is my HTML
<form action="feedback.php" method="post">
<table>
<tr>
<td>Email Address:</td>
<td>
<input type="text" name="email_address" value="" maxlength="100" />
</td>
</tr>
<tr>
<td>
Comments:
</td>
<td>
<textarea rows="10" cols="50" name="comments">
</textarea>
</td>
</tr>
<tr>
<td> </td>
<td>
<input type="submit" value="Submit" />
</td>
</tr>
</table>
</form>
Here is my php:
<?php
$email_address = $_POST['email_address'];
$comments = $_POST['comments'];
$myfile = fopen("feedback.txt", "a") or die("Unable to open file!");
$txt = 'Email: '.$email.'\nComments: '.$comments.'\n\n';
fwrite($myfile, $txt);
fclose($myfile);
?>
So I need different comments to save to different line rather than just one.
Your \n (new line) is not working because you use apostrophe ' instead of double quotes ".
eg you have:
$txt='Email: '.$email.'\nComments: '.$comments.'\n\n';
And you need:
$txt="Email: ".$email."\nComments: ".$comments."\n\n";
EDIT
Your email address isn't being written as you change the variable name used.
e.g. You have this code:
$email_address=$_POST['email_address'];
$txt='Email: '.$email.'\nComments: '.$comments.'\n\n';
Your $txt variable is using $email however you're setting the $_POST data to variable $email_address.
Try this complete code:
$email_address = $_POST['email_address'];
$comments = $_POST['comments'];
$myfile = fopen("feedback.txt", "a") or die("Unable to open file!");
$txt="Email: ".$email_address."\nComments: ".$comments."\n\n";
fwrite($myfile, $txt);
fclose($myfile);
It's a simple mistake to make, but you should try to get into the habit of copying and pasting your variable names, rather than re-typing them. This (helps) avoid typos etc, which in large code blocks & multiple files, becomes an even bigger problem.
And use your error logs - they are invaluable when coding!
In this case PHP (thus the logs) would have moaned about that $email variable not being defined, which in turn would have led you to inspect the variable and you'd have likely worked it out.
I Would use PHP_EOL since it's cross-platform-compatible! That means it handles Unix/DOS/Mac issues!
(Also i think you want to change the $email variable)
So insteat your line:
$txt='Email: '.$email.'\nComments: '.$comments.'\n\n';
Use:
$txt = "Email: ". $email_address . PHP_EOL . "Comments: " . $comments . PHP_EOL . PHP_EOL;
$txt='Email: '.$email.'\nComments: '.$comments.'\n\n';
Use \r\n to make new line text file like:
$txt='Email: '.$email.'\r\n Comments: '.$comments.'\r\n';
You actually may use single quotes and concatenate a newline character but you'd need to write code like this:
<?php
echo 'This is a test of using a newline char.' . chr(10) .
'Did it work? It should have.';
?>
To reduce the possibility of things going wrong one should do certain checks. Did the user actually submit a form? Also, we should not assume that all data from $_POST is safe and hence I use htmlentities() for the email address and the comments, just in case a malicious user tries to slip in something they shouldn't.
The other point is that some people think that variable interpolation is slow but the ironic thing is that the more variable interpolation there is the more efficient that interpolation processing becomes. Incidentally, I changed some of the newlines by adding some and removing others so that the final result is formatted in a way that is easier to read.
<?php
if (isset($_POST) && $_POST != NULL) {
$email_address = htmlentities($_POST['email_address']);
$comments = htmlentities($_POST['comments']);
$myfile = fopen("feedback.txt", "a") or exit("Unable to open file!");
$txt="Email: $email_address\nComments:\n\n$comments\n\n";
fwrite($myfile, $txt);
fclose($myfile);
}
?>
I replaced the morbid die() with exit() since they are both equivalent language constructs; they both generate the same EXIT opcode.
Related
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.
I am trying to make a website where you input a value to order food. In php i am trying to make it create a txt file that i can view. I have gotten it to make the file, but instead of a number, it simply displays 'Fries: Array' and the 'Array' should be a number. My php and HTML code is as follows...
HTML:
<input type="number" name="Fries" min="0" max="69"><br>
PHP:
<?php
$path = "Fries.txt";
$fh = fopen("Fries.txt", "w") or die("Unable to open file!");
$fries = array(['Fries']);
$string = 'Fries: '. strval($fries[0]);
fwrite($fh, $string);
fclose($fh);
?>`
If anyone can tell me how to get php to read HTML form data, that wiuld be great
Assuming that you're aware of all of the potential pitfalls of taking user input and writing it to a file without any type of validation: square brackets in PHP are a shortcut for defining a new array. So what you've written is equivalent to:
$fries = array(array('Fries'));
Also, you're assigning your new array the string value "fries," when you say you're trying to get this from your user input. Try the following:
...
$fries = 'Fries: ' . $_REQUEST['Fries'];
fwrite($fh, $string);
...
No need to use strval() - value is already a string.
And as far as validation, you may want to add the following before you assign your $fries variable:
if (is_numeric($_REQUEST['Fries'] && $_REQUEST['Fries'] >= 0 && $_REQUEST['Fries'] <= 69)
HTML:
<form method="post">
<input type="number" name="fries" min="0" max="69"><br>
<input type="submit" name="submit">
</form>
PHP:
<?php
$path = "Fries.txt";
$fh = fopen($path, "w") or die("Unable to open file!");
$string = 'Fries: '. filter_input(INPUT_POST,'fries');
fwrite($fh, $string);
fclose($fh);
?>
<form action="editinfo.php" method="post">
<pre><textarea rows="440" name="editinfo" cols="700"></textarea></pre><br><br>
<input type="submit" class="ButtonSub" value="Submit">
</form>
editinfo.php
$editinfo = mysqli_real_escape_string($connd, $_POST['editinfo']);
$myfile = fopen("myinfo.txt", "wb") or die("Unable to open file!");
fwrite($myfile, $editinfo);
fclose($myfile);
What I want to achieve?
Let's say I have editinfo text is
SAM
PLEM
it outputs SAM\r\nPLEM in the txt, how can I format it correctly? so it can look like
SAM
PLEM
Simply don't SQL-escape (mysqli_real_escape_string) the text, that's what's turning a linebreak into escaped \r\n sequences. There's absolutely no point in SQL escaping something that isn't going to be used in an SQL query.
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.
Ok, so I have a form that takes a username and a code. This is then passed to php for processing. I am not super php saavy, so I want to be able to take a specific portion of the out put and write it to a text file, this form would be used over and over, and I want the text to be appended to the file. As you can see from the output I'm looking to capture, it's basically writing to some code that will be used for usernames in a css. So here is what I have...
The HTML Form
<html><body>
<h4>Codes Form</h4>
<form action="codes.php" method="post">
Username: <input name="Username" type="text" />
Usercode: <input name="Usercode" type="text" />
<input type="submit" value="Post It!" />
</form>
</body></html>
The PHP
--><html><body>
<?php
$Usercode = $_POST['Usercode'];
$Username = $_POST['Username'];
echo "You have recorded the following in our system ". $Username . " " . $Usercode . ".<br />";
echo "Thanks for contributing!";
echo .author[href$="/$Username"]:after {
echo content: "($Usercode)"
echo }
?>
</body></html>
All that I would like to be written to the text file would be this portion..
--> .author[href$="/$Username"]:after {
content: "($Usercode)"
}
Basically, the text file would have line after line of that exact same code, but with different usernames and usercodes. Hopefully, the variable $Usercode and $Username can also be captured and written into the output in the manner that I have it written. I'm just baffled by output buffering in php and clean and flush etc, and fwrite doesn't seem to be able to write without wiping a file clean each time it writes to it. I may be wrong of course. Anyone care to help?
Try this:
<?php
$output = "--> .author[href=$Username]:after { \n"
."content: ($Usercode)\n"
."}";
$fp = fopen($file, 'a');
fwrite($fp, $output);
fwrite($fp, "\n");
fclose($fp);
?>
The flag a will open already a text file and place the pointer to the end of file, so this will not overwrite your already file, more information in fopen.
You can use the function file_put_contents($file, $data, FILE_APPEND); where $file is the path of the file you are writing to, data is the whatever value you are writing to the file. This assumes you are using php5. If not, you will have to create a handle with fopen, write to the file with fwrite and end with fclose to close the file pointed to in your fopen handle.