텍스트 파일에서 작성 또는 쓰기 / 추가
사용자가 로그인하거나 로그 아웃 할 때마다 텍스트 파일로 저장하는 웹 사이트가 있습니다.
데이터를 추가하거나 텍스트 파일이없는 경우 내 코드가 작동하지 않습니다. 샘플 코드는 다음과 같습니다.
$myfile = fopen("logs.txt", "wr") or die("Unable to open file!");
$txt = "user id date";
fwrite($myfile, $txt);
fclose($myfile);
다시 열면 다음 줄에 추가되지 않는 것 같습니다.
또한 2 명의 사용자가 동시에 로그인 할 때 오류가 발생한다고 생각합니다. 텍스트 파일을 열고 나중에 저장하는 데 영향을 줍니까?
다음과 같이 해보십시오 :
$txt = "user id date";
$myfile = file_put_contents('logs.txt', $txt.PHP_EOL , FILE_APPEND | LOCK_EX);
a
모드를 사용하십시오 . 의 약자입니다 append
.
$myfile = fopen("logs.txt", "a") or die("Unable to open file!");
$txt = "user id date";
fwrite($myfile, "\n". $txt);
fclose($myfile);
대안적이고 유연한 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;
}
}
그런 다음 다음과 같이 사용하십시오. 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
코드에는 "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/
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.
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'.
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.
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.
Here is what you need, as has been already pointed out above:
fopen("logs.txt", "a")
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...
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);
}
}
This is working for me, Writing(creating as well) and/or appending content in the same mode.
$fp = fopen("MyFile.txt", "a+")
참고URL : https://stackoverflow.com/questions/24972424/create-or-write-append-in-text-file
'Programming' 카테고리의 다른 글
Java / Spring에서 Scala / Lift를 사용하는 이유는 무엇입니까? (0) | 2020.06.09 |
---|---|
MySQL 외래 키 제약 조건, 계단식 삭제 (0) | 2020.06.09 |
오버플로 된 Div 내의 요소로 어떻게 스크롤합니까? (0) | 2020.06.09 |
MSI를 통해 제거 할 때만 발생하는 WiX 사용자 지정 동작을 추가하는 방법은 무엇입니까? (0) | 2020.06.09 |
“select from”을 사용하지 않고 테이블이 존재하는지 확인 (0) | 2020.06.09 |