Hack Forums
[PHP] How to make .php write only one line in data.txt or make a new file evert time? - Printable Version

+- Hack Forums (https://hackforums.net)
+-- Forum: Tech (https://hackforums.net/forumdisplay.php?fid=444)
+--- Forum: Coding (https://hackforums.net/forumdisplay.php?fid=151)
+---- Forum: Web Development (https://hackforums.net/forumdisplay.php?fid=183)
+---- Thread: [PHP] How to make .php write only one line in data.txt or make a new file evert time? (/showthread.php?tid=5802189)



How to make .php write only one line in data.txt or make a new file evert time? - t0pemie - Feb 20, 2018

I want to make that .php to make write only one line in "data.txt" or make a new text file every time.
How should i do it?

<?php
header('Location: https://www.xxx.com');
$txt = "data.txt";
$fh = fopen($txt, 'w+');
if (isset($_POST['field1']) && isset($_POST['field2'])) { // check if both fields are set
$txt=$_POST['field1'].' - '.$_POST['field2'];
file_put_contents('data.txt',$txt."\n",FILE_APPEND); //log to data.txt
exit();
}
fwrite($fh,$txt); // write information to the file
fclose($fh); // close the file

?>?


RE: Would someone compound this little .php code to little .html code? - Devsoft - Feb 20, 2018

Not really sure what exactly are you asking.
The PHP part MUST be above all of your HTML, and form should be in the body of the HTML.


RE: Would someone compound this little .php code to little .html code? - BrainDeadGenius - Feb 20, 2018

Why are you sending login information via text file?


RE: How to make .php write only one line in data.txt or make a new file evert time? - gigajew - Feb 20, 2018

$fileHandle = fopen(‘filename’, ‘a’);
fwrite($fileHandle, ‘new line\r\n’);
fclose($fileHandle);


RE: How to make .php write only one line in data.txt or make a new file evert time? - V3t3r4n - Feb 20, 2018

If I understood right, you want the file to only one line every time (The most recent one)? If so, your code is fine, just take off the FILE_APPEND flag from your function, and if the file exists, it always creates a new one and overwrites the current one.

So this line:
PHP Code

<?php 
file_put_contents
('data.txt',$txt."\n",FILE_APPEND); //log to data.txt 

Should look like this:
PHP Code

<?php 
file_put_contents
('data.txt',$txt); //log to data.txt 

That's it!

You can read about the function here: https://secure.php.net/manual/en/function.file-put-contents.php, it has a section describing what each flags does, and what the function normal behavior should look like :)