我有一个网站,每当一个用户登录或注销,我将它保存到一个文本文件。

我的代码不能在追加数据或创建一个文本文件,如果它不存在..下面是示例代码

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

当我再次打开它时,它似乎没有附加到下一行。

我也认为它也会有一个错误的情况下,当2个用户登录在同一时间,它会影响打开文本文件和保存它之后?


当前回答

试试下面的代码:

function logErr($data){
  $logPath = __DIR__. "/../logs/logs.txt";
  $mode = (!file_exists($logPath)) ? 'w':'a';
  $logfile = fopen($logPath, $mode);
  fwrite($logfile, "\r\n". $data);
  fclose($logfile);
}

我总是这样使用它,而且它很有效……

其他回答

试试这样做:

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

试试下面的代码:

function logErr($data){
  $logPath = __DIR__. "/../logs/logs.txt";
  $mode = (!file_exists($logPath)) ? 'w':'a';
  $logfile = fopen($logPath, $mode);
  fwrite($logfile, "\r\n". $data);
  fclose($logfile);
}

我总是这样使用它,而且它很有效……

这是为我工作,写作(创建以及)和/或附加内容在相同的模式。

$fp = fopen("MyFile.txt", "a+") 

使用a模式。它代表附加。

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

尽管有很多方法可以做到这一点。但如果你想以一种简单的方式来做,并希望在将文本写入日志文件之前格式化文本。您可以为此创建一个辅助函数。

if (!function_exists('logIt')) {
    function logIt($logMe)
    {
        $logFilePath = storage_path('logs/cron.log.'.date('Y-m-d').'.log');
        $cronLogFile = fopen($logFilePath, "a");
        fwrite($cronLogFile, date('Y-m-d H:i:s'). ' : ' .$logMe. PHP_EOL);
        fclose($cronLogFile);
    }
}