我有一个网站,每次用户登录或注销我都会将其保存到文本文件.
我的代码在附加数据时不起作用,或者如果不存在则创建文本文件.这里是示例代码
$myfile = fopen("logs.txt", "wr") or die("Unable to open file!");
$txt = "user id date";
fwrite($myfile, $txt);
fclose($myfile);
Run Code Online (Sandbox Code Playgroud)
但是在我再次打开之后,它似乎不会附加到下一行.
也.我认为如果2个用户同时登录会影响打开文本文件并保存之后会出现错误吗?
Spe*_*erX 307
尝试这样的事情:
$txt = "user id date";
$myfile = file_put_contents('logs.txt', $txt.PHP_EOL , FILE_APPEND | LOCK_EX);
Run Code Online (Sandbox Code Playgroud)
Val*_*ier 98
使用a模式.它代表着append.
$myfile = fopen("logs.txt", "a") or die("Unable to open file!");
$txt = "user id date";
fwrite($myfile, "\n". $txt);
fclose($myfile);
Run Code Online (Sandbox Code Playgroud)
你可以用OO的方式做到这一点,只是一种替代性和灵活性:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
然后像这样使用..让我们说你已经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"]);
}
Run Code Online (Sandbox Code Playgroud)
用这个检查你的日志:
$log->getLog();
Run Code Online (Sandbox Code Playgroud)
结果如下:
Sun Jul 02 '17 05.45 PM » Successful Login: JohnDoe
Sun Jul 02 '17 05.46 PM » Logout: JohnDoe
Run Code Online (Sandbox Code Playgroud)
这对我有用,写作(也创造)和/或以相同的模式附加内容。
$fp = fopen("MyFile.txt", "a+")
Run Code Online (Sandbox Code Playgroud)
尽管有很多方法可以做到这一点。但是,如果您想以简单的方式完成此操作,并希望在将文本写入日志文件之前对其进行格式化。您可以为此创建一个辅助函数。
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);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
248097 次 |
| 最近记录: |