我有一个网站,每当一个用户登录或注销,我将它保存到一个文本文件。
我的代码不能在追加数据或创建一个文本文件,如果它不存在..下面是示例代码
$myfile = fopen("logs.txt", "wr") or die("Unable to open file!");
$txt = "user id date";
fwrite($myfile, $txt);
fclose($myfile);
当我再次打开它时,它似乎没有附加到下一行。
我也认为它也会有一个错误的情况下,当2个用户登录在同一时间,它会影响打开文本文件和保存它之后?
你可以用面向对象的方式来做,这是一种灵活的选择:
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