php 在文本文件中创建或写入/追加
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24972424/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create or write/append in text file
提问by Jerahmeel Acebuche
I have a website that every time a user logs in or logs out I save it to a text file.
我有一个网站,每次用户登录或注销时,我都会将其保存到文本文件中。
My code doesn't work in appending data or creating a text file if it 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);
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 when 2 users login at the same time, would it affect opening the text file and saving it afterwards?
另外我认为在2个用户同时登录的情况下也会出错,会影响打开文本文件并在之后保存吗?
回答by SpencerX
Try something like this:
尝试这样的事情:
$txt = "user id date";
$myfile = file_put_contents('logs.txt', $txt.PHP_EOL , FILE_APPEND | LOCK_EX);
回答by Valentin Mercier
Use the a
mode. It stands for append
.
使用a
模式。它代表append
.
$myfile = fopen("logs.txt", "a") or die("Unable to open file!");
$txt = "user id date";
fwrite($myfile, "\n". $txt);
fclose($myfile);
回答by Thielicious
You can do it the OO way, just an alternative and flexible:
你可以用面向对象的方式来做,只是一种替代和灵活的方式:
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;
}
}
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
回答by Mihir Bhatt
This is working for me, Writing(creating as well) and/or appending content in the same mode.
这对我有用,写作(也创造)和/或以相同的模式附加内容。
$fp = fopen("MyFile.txt", "a+")
回答by Rwakos
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...
我总是这样使用它,它有效......
回答by Maxim Masiutin
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.phpis 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 标准添加了 PHP 支持的新标准子说明符(“x”),可以附加到任何“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 标志。仅在符合 POSIX.1-2008 的系统上编译的 PHP 中可用。
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")
回答by PHP Worm...
Although there are many ways to do this. But if you want to do it in an easy way and want to format text before writing it to log file. You can create a helper function for this.
虽然有很多方法可以做到这一点。但是,如果您想以简单的方式进行操作并希望在将文本写入日志文件之前对其进行格式化。您可以为此创建一个辅助函数。
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);
}
}