I'm trying to write username and password to a new line in a txt file. The output should be something like this in the txt file. I know this is not very secure but its just for learning purposes
Sebastian password John hfsjaijn
This is what i have so far
if(isset($_GET['register'])) // { $user = $_GET['username']; $password=$_GET['password']; $fh = fopen("file.txt","a+"); fwrite($fh,$user."\n"); //write to txtfile fwrite($fh,$password."\n"); // write to txtfile fclose($fh); }
EDIT: Here's the solution for me:
if (isset($_POST['register'])) { $user = $_POST['username']; $password = $_POST['password'].PHP_EOL; $fh = fopen("file.txt","a+"); fwrite($fh,$user." ".$password); //write to txtfile fclose($fh); }
When writing to a file in PHP with fwrite , you can add a newline character with PHP_EOL. Using PHP_EOL instead of manually writing out a "\n" or "\r\n" is important to make your code as portable as possible.
PHP fwrite() Function$file = fopen("test. txt","w"); echo fwrite($file,"Hello World. Testing!");
fwrite() allows to write to file a byte or block of bytes at a time, file_put_content() writes the entire file in one go.... which is better? depends what you need to do! and on the volumes of data that you want to write! fwrite requires a handle while file_put_contents does not.
The fwrite() function in PHP is an inbuilt function which is used to write to an open file.
Use PHP_EOL
which produces \r\n
or \n
$data = 'my data' . PHP_EOL . 'my data'; $fp = fopen('my_file', 'a'); fwrite($fp, $data); fclose($fp);
// File output
my data my data
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With