I have a website that every time a user login or logout I will save it to a text file.
我有一个网站,每次用户登录或登出时,我都会把它保存到一个文本文件中。
my code doesn't work in appending the data or creates a text file if does not exist.. here is the sample code
如果不存在,我的代码不会在附加数据或创建文本文件时工作。这是示例代码
$myfile = fopen("logs.txt", "wr") or die("Unable to open file!");
$txt = "user id date";
fwrite($myfile, $txt);
fclose($myfile);
but it seems it does not append to next line after i open it again.
但似乎在我再次打开后,它并没有附加到下一行。
also. I think it would also have an error in a situation like what if 2 users login on the same time would it affect opening the text file and saving it after?
也。我认为它也会有一个错误,如果两个用户同时登录,会不会影响打开文本文件然后保存?
6 个解决方案
#1
200
Try something like this:
试试这样:
$txt = "user id date";
$myfile = file_put_contents('logs.txt', $txt.PHP_EOL , FILE_APPEND | LOCK_EX);
#2
60
Use the a
mode. It stands for append
.
使用的模式。它所代表的附加。
$myfile = fopen("logs.txt", "a") or die("Unable to open file!");
$txt = "user id date";
fwrite($myfile, "\n". $txt);
fclose($myfile);
#3
3
You can do it the OO way, just an alternative and flexible:
你可以用OO的方式做,只是一种选择和灵活的方式:
class Logger {
private
$file,
$prefix;
public function __construct($filename) {
$this->file = $filename;
}
public function setTimestamp($format) {
$this->prefix = date($format)." » ";
}
public function putLog($insert) {
if (isset($this->prefix)) {
file_put_contents($this->file, $this->prefix.$insert."<br>", FILE_APPEND);
} else {
echo "<script>alert(\"Timestamp is not set yet.\");</script>", die;
}
}
public function getLog() {
$content = @file_get_contents($this->file);
return $content;
}
}
Then use it like this .. let's say you have user_name
stored in a session (semi pseudo code):
然后像这样使用它。假设您有一个存储在会话中的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"]);
}
Check your log with this:
检查你的日志如下:
$log->getLog();
Result is like:
结果是:
Sun Jul 02 '17 05.45 PM » Successful Login: JohnDoe
Sun Jul 02 '17 05.46 PM » Logout: JohnDoe
github.com/thielicious/Logger
#4
1
There is no such file open mode as "wr" in your code:
您的代码中没有“wr”这样的文件打开模式:
fopen("logs.txt", "wr")
The file open modes in PHP http://php.net/manual/en/function.fopen.php is the same as in C: http://www.cplusplus.com/reference/cstdio/fopen/
PHP中的文件打开模式http://php.net/manual/en/function.fopen.php与C中的相同:http://www.cplusplus.com/reference/cstdio/fopen/
There are the following main open modes "r" for read, "w" for write and "a" for append, and you cannot combine them. You can add other modifiers like "+" for update, "b" for binary. The new C standard adds a new standard subspecifier ("x"), supported by PHP, that can be appended to any "w" specifier (to form "wx", "wbx", "w+x" or "w+bx"/"wb+x"). This subspecifier forces the function to fail if the file exists, instead of overwriting it.
有以下主要的开放模式“r”为读,“w”为写,“a”为附加,你不能合并它们。您可以添加其他修饰符,如“+”用于更新,“b”用于二进制。新的C标准添加了一个新的标准subspecifier(“x”),由PHP支持,可以添加到任何“w”说明符(形成“wx”、“wbx”、“w+x”或“w+bx”/“wb+x”)。如果文件存在,该子说明符强制函数失败,而不是覆盖它。
Besides that, in PHP 5.2.6, the 'c' main open mode was added. You cannot combine 'c' with 'a', 'r', 'w'. The 'c' opens the file for writing only. If the file does not exist, it is created. If it exists, it is neither truncated (as opposed to 'w'), nor the call to this function fails (as is the case with 'x'). 'c+' Open the file for reading and writing; otherwise it has the same behavior as 'c'.
此外,在PHP 5.2.6中,添加了“c”主打开模式。你不能把“c”和“a”、“r”、“w”组合在一起。“c”打开文件只供编写。如果文件不存在,则创建该文件。如果它存在,它既不会被截断(与“w”相对),也不会调用该函数失败(与“x”一样)。“c+”打开文件进行读写;否则,它的行为与“c”相同。
Additionally, and in PHP 7.1.2 the 'e' option was added that can be combined with other modes. It set close-on-exec flag on the opened file descriptor. Only available in PHP compiled on POSIX.1-2008 conform systems.
此外,在PHP 7.1.2中添加了可以与其他模式结合的“e”选项。它在打开的文件描述符上设置close-on-exec标志。只有在PHP编译的POSIX.1-2008一致性系统中才可用。
So, for the task as you have described it, the best file open mode would be 'a'. It opens the file for writing only. It places the file pointer at the end of the file. If the file does not exist, it attempts to create it. In this mode, fseek() has no effect, writes are always appended.
因此,对于您所描述的任务,最好的文件打开模式是“a”。它只打开文件进行写入。它将文件指针放在文件的末尾。如果该文件不存在,它将尝试创建它。在这种模式下,fseek()不起作用,写入总是被追加。
Here is what you need, as has been already pointed out above:
这是你需要的,正如上面已经指出的:
fopen("logs.txt", "a")
#5
0
Try this code:
试试这段代码:
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);
}
I always use it like this, and it works...
我总是像这样使用它,它可以……
#6
0
In Codeigniter you can use FILE_APPEND method
在Codeigniter中,您可以使用FILE_APPEND方法
$logged_user_id = $this->session->userdata('user_id');
$insert_log = 'process => 'YOUR PROCESS STATUS TO LOG', user_id => '.$logged_user_id.',reg_at => '.date("d/m/Y h:i:sa");
$Dt = date('d-m-Y');
file_put_contents(APPPATH."assets/logs/".$Dt."_log.txt", $insert_log.PHP_EOL , FILE_APPEND | LOCK_EX);
This Log can be created and append data in daily basis.
可以创建该日志并按日添加数据。
#1
200
Try something like this:
试试这样:
$txt = "user id date";
$myfile = file_put_contents('logs.txt', $txt.PHP_EOL , FILE_APPEND | LOCK_EX);
#2
60
Use the a
mode. It stands for append
.
使用的模式。它所代表的附加。
$myfile = fopen("logs.txt", "a") or die("Unable to open file!");
$txt = "user id date";
fwrite($myfile, "\n". $txt);
fclose($myfile);
#3
3
You can do it the OO way, just an alternative and flexible:
你可以用OO的方式做,只是一种选择和灵活的方式:
class Logger {
private
$file,
$prefix;
public function __construct($filename) {
$this->file = $filename;
}
public function setTimestamp($format) {
$this->prefix = date($format)." » ";
}
public function putLog($insert) {
if (isset($this->prefix)) {
file_put_contents($this->file, $this->prefix.$insert."<br>", FILE_APPEND);
} else {
echo "<script>alert(\"Timestamp is not set yet.\");</script>", die;
}
}
public function getLog() {
$content = @file_get_contents($this->file);
return $content;
}
}
Then use it like this .. let's say you have user_name
stored in a session (semi pseudo code):
然后像这样使用它。假设您有一个存储在会话中的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"]);
}
Check your log with this:
检查你的日志如下:
$log->getLog();
Result is like:
结果是:
Sun Jul 02 '17 05.45 PM » Successful Login: JohnDoe
Sun Jul 02 '17 05.46 PM » Logout: JohnDoe
github.com/thielicious/Logger
#4
1
There is no such file open mode as "wr" in your code:
您的代码中没有“wr”这样的文件打开模式:
fopen("logs.txt", "wr")
The file open modes in PHP http://php.net/manual/en/function.fopen.php is the same as in C: http://www.cplusplus.com/reference/cstdio/fopen/
PHP中的文件打开模式http://php.net/manual/en/function.fopen.php与C中的相同:http://www.cplusplus.com/reference/cstdio/fopen/
There are the following main open modes "r" for read, "w" for write and "a" for append, and you cannot combine them. You can add other modifiers like "+" for update, "b" for binary. The new C standard adds a new standard subspecifier ("x"), supported by PHP, that can be appended to any "w" specifier (to form "wx", "wbx", "w+x" or "w+bx"/"wb+x"). This subspecifier forces the function to fail if the file exists, instead of overwriting it.
有以下主要的开放模式“r”为读,“w”为写,“a”为附加,你不能合并它们。您可以添加其他修饰符,如“+”用于更新,“b”用于二进制。新的C标准添加了一个新的标准subspecifier(“x”),由PHP支持,可以添加到任何“w”说明符(形成“wx”、“wbx”、“w+x”或“w+bx”/“wb+x”)。如果文件存在,该子说明符强制函数失败,而不是覆盖它。
Besides that, in PHP 5.2.6, the 'c' main open mode was added. You cannot combine 'c' with 'a', 'r', 'w'. The 'c' opens the file for writing only. If the file does not exist, it is created. If it exists, it is neither truncated (as opposed to 'w'), nor the call to this function fails (as is the case with 'x'). 'c+' Open the file for reading and writing; otherwise it has the same behavior as 'c'.
此外,在PHP 5.2.6中,添加了“c”主打开模式。你不能把“c”和“a”、“r”、“w”组合在一起。“c”打开文件只供编写。如果文件不存在,则创建该文件。如果它存在,它既不会被截断(与“w”相对),也不会调用该函数失败(与“x”一样)。“c+”打开文件进行读写;否则,它的行为与“c”相同。
Additionally, and in PHP 7.1.2 the 'e' option was added that can be combined with other modes. It set close-on-exec flag on the opened file descriptor. Only available in PHP compiled on POSIX.1-2008 conform systems.
此外,在PHP 7.1.2中添加了可以与其他模式结合的“e”选项。它在打开的文件描述符上设置close-on-exec标志。只有在PHP编译的POSIX.1-2008一致性系统中才可用。
So, for the task as you have described it, the best file open mode would be 'a'. It opens the file for writing only. It places the file pointer at the end of the file. If the file does not exist, it attempts to create it. In this mode, fseek() has no effect, writes are always appended.
因此,对于您所描述的任务,最好的文件打开模式是“a”。它只打开文件进行写入。它将文件指针放在文件的末尾。如果该文件不存在,它将尝试创建它。在这种模式下,fseek()不起作用,写入总是被追加。
Here is what you need, as has been already pointed out above:
这是你需要的,正如上面已经指出的:
fopen("logs.txt", "a")
#5
0
Try this code:
试试这段代码:
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);
}
I always use it like this, and it works...
我总是像这样使用它,它可以……
#6
0
In Codeigniter you can use FILE_APPEND method
在Codeigniter中,您可以使用FILE_APPEND方法
$logged_user_id = $this->session->userdata('user_id');
$insert_log = 'process => 'YOUR PROCESS STATUS TO LOG', user_id => '.$logged_user_id.',reg_at => '.date("d/m/Y h:i:sa");
$Dt = date('d-m-Y');
file_put_contents(APPPATH."assets/logs/".$Dt."_log.txt", $insert_log.PHP_EOL , FILE_APPEND | LOCK_EX);
This Log can be created and append data in daily basis.
可以创建该日志并按日添加数据。