PHP fwrite new line

Php

Php Problem Overview


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);
}

Php Solutions


Solution 1 - Php

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

Solution 2 - Php

You append a newline to both the username and the password, i.e. the output would be something like

Sebastian
password
John
hfsjaijn

use fwrite($fh,$user." ".$password."\n"); instead to have them both on one line.
Or use http://docs.php.net/fputcsv">fputcsv()</a> to write the data and fgetcsv() to fetch it. This way you would at least avoid encoding problems like e.g. with $username='Charles, III';

...i.e. setting aside all the things that are wrong about storing plain passwords in plain files and using _GET for this type of operation (use _POST instead) ;-)

Solution 3 - Php

fwrite($handle, "<br>"."\r\n");

Add this under

$password = $_POST['password'].PHP_EOL;

this. .

Solution 4 - Php

How about you store it like this? Maybe in username:password format, so

sebastion:password123
anotheruser:password321

Then you can use list($username,$password) = explode(':',file_get_contents('users.txt')); to parse the data on your end.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDynamiiteView Question on Stackoverflow
Solution 1 - PhpDino BabuView Answer on Stackoverflow
Solution 2 - PhpVolkerKView Answer on Stackoverflow
Solution 3 - PhpThrallixView Answer on Stackoverflow
Solution 4 - PhpMark AdewaleView Answer on Stackoverflow