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

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

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

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

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


当前回答

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

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

其他回答

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

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

试试这样做:

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

你可以用面向对象的方式来做,这是一种灵活的选择:

class Logger {

    private
        $file,
        $timestamp;

    public function __construct($filename) {
        $this->file = $filename;
    }

    public function setTimestamp($format) {
        $this->timestamp = date($format)." » ";
    }

    public function putLog($insert) {
        if (isset($this->timestamp)) {
            file_put_contents($this->file, $this->timestamp.$insert."<br>", FILE_APPEND);
        } else {
            trigger_error("Timestamp not set", E_USER_ERROR);
        }
    }

    public function getLog() {
        $content = @file_get_contents($this->file);
        return $content;
    }

}

然后像这样使用它。假设你把user_name存储在一个会话中(半伪代码):

$log = new Logger("log.txt");
$log->setTimestamp("D M d 'y h.i A");

if (user logs in) {
    $log->putLog("Successful Login: ".$_SESSION["user_name"]);
}
if (user logs out) {
    $log->putLog("Logout: ".$_SESSION["user_name"]);
}

用这个检查你的日志:

$log->getLog();

结果如下:

Sun Jul 02 '17 05.45 PM » Successful Login: JohnDoe
Sun Jul 02 '17 05.46 PM » Logout: JohnDoe

github.com/thielicious/Logger

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

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

试试下面的代码:

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

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