簡體   English   中英

PHP 寫入新行

[英]PHP fwrite new line

我正在嘗試將用戶名和密碼寫入 txt 文件中的新行。 txt 文件中的輸出應該是這樣的。 我知道這不是很安全,但僅用於學習目的

Sebastian   password
John        hfsjaijn

這是我到目前為止

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

編輯:這是我的解決方案:

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_EOL產生\\r\\n\\n

$data = 'my data' . PHP_EOL . 'my data';
$fp = fopen('my_file', 'a');
fwrite($fp, $data);
fclose($fp);

// 文件輸出

my data
my data

您在用戶名密碼后附加一個換行符,即輸出將類似於

Sebastian
password
John
hfsjaijn

使用fwrite($fh,$user." ".$password."\\n"); 而是將它們都放在一行上。
或者使用fputcsv()寫入數據並使用fgetcsv()獲取它。 這樣你至少可以避免編碼問題,例如$username='Charles, III';

...即拋開將普通密碼存儲在普通文件中並使用 _GET 進行此類操作(使用 _POST 代替)的所有錯誤;-)

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

在下面添加這個

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

這。 .

你這樣存放怎么樣? 也許是用戶名:密碼格式,所以

sebastion:password123
anotheruser:password321

然后你可以使用list($username,$password) = explode(':',file_get_contents('users.txt')); 解析你的數據。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM