我有一个网站,每当一个用户登录或注销,我将它保存到一个文本文件。
我的代码不能在追加数据或创建一个文本文件,如果它不存在..下面是示例代码
$myfile = fopen("logs.txt", "wr") or die("Unable to open file!");
$txt = "user id date";
fwrite($myfile, $txt);
fclose($myfile);
当我再次打开它时,它似乎没有附加到下一行。
我也认为它也会有一个错误的情况下,当2个用户登录在同一时间,它会影响打开文本文件和保存它之后?
在你的代码中没有“wr”这样的文件打开模式:
fopen("logs.txt", "wr")
PHP http://php.net/manual/en/function.fopen.php中的文件打开模式与C: http://www.cplusplus.com/reference/cstdio/fopen/相同
有以下几种主要的打开模式“r”用于读,“w”用于写,“a”用于追加,不能将它们组合起来。您可以添加其他修饰符,如“+”表示更新,“b”表示二进制。新的C标准增加了一个新的标准子说明符("x"),由PHP支持,可以附加到任何"w"说明符(形成"wx", "wbx", "w+x"或"w+bx"/"wb+x")。如果文件存在,该子说明符将强制函数失败,而不是覆盖它。
此外,在PHP 5.2.6中,添加了'c'主打开模式。你不能把“c”和“a”、“r”、“w”结合起来。“c”打开文件仅用于写入。如果该文件不存在,则创建该文件。如果它存在,它既不会被截断(与'w'相反),也不会调用该函数失败(与'x'一样)。打开文件进行读写;否则它和c有相同的行为。
此外,在PHP 7.1.2中增加了'e'选项,可以与其他模式组合。它在打开的文件描述符上设置close-on-exec标志。仅在POSIX.1-2008符合系统的PHP编译中可用。
所以,对于你所描述的任务,最好的文件打开模式是“a”。它只打开文件进行写入。它将文件指针放在文件的末尾。如果该文件不存在,则尝试创建该文件。在这种模式下,fseek()不起作用,总是追加写操作。
以下是你所需要的,正如上面已经指出的:
fopen("logs.txt", "a")
你可以用面向对象的方式来做,这是一种灵活的选择:
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