在文本文件中创建或写入/追加

php
2022-08-30 06:24:01

我有一个网站,每次用户登录或注销时,我都会将其保存到文本文件中。

我的代码在追加数据或创建文本文件(如果不存在)时不起作用。下面是示例代码

$myfile = fopen("logs.txt", "wr") or die("Unable to open file!");
$txt = "user id date";
fwrite($myfile, $txt);
fclose($myfile);

在我再次打开它后,它似乎不会附加到下一行。

另外,我认为在2个用户同时登录的情况下也会有错误,这会影响打开文本文件并在之后保存它吗?


答案 1

试试下面这样:

 $txt = "user id date";
 $myfile = file_put_contents('logs.txt', $txt.PHP_EOL , FILE_APPEND | LOCK_EX);

答案 2

使用该模式。它代表 .aappend

$myfile = fopen("logs.txt", "a") or die("Unable to open file!");
$txt = "user id date";
fwrite($myfile, "\n". $txt);
fclose($myfile);

推荐