Create or write/append in text file

Php

Php Problem Overview


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?

Php Solutions


Solution 1 - Php

Try something like this:

 $txt = "user id date";
 $myfile = file_put_contents('logs.txt', $txt.PHP_EOL , FILE_APPEND | LOCK_EX);

Solution 2 - Php

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);

Solution 3 - Php

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):

$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

Solution 4 - Php

> This is working for me, Writing(creating as well) and/or appending content in the same mode.

$fp = fopen("MyFile.txt", "a+") 

Solution 5 - Php

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...

Solution 6 - Php

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);
    }
}

Solution 7 - Php

There is no such file open mode as "wr" in your code:

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") 

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJerahmeel AcebucheView Question on Stackoverflow
Solution 1 - PhpSpencerXView Answer on Stackoverflow
Solution 2 - PhpValentin MercierView Answer on Stackoverflow
Solution 3 - PhpThieliciousView Answer on Stackoverflow
Solution 4 - PhpMihir BhattView Answer on Stackoverflow
Solution 5 - PhpRwakosView Answer on Stackoverflow
Solution 6 - PhpPHP Worm...View Answer on Stackoverflow
Solution 7 - PhpMaxim MasiutinView Answer on Stackoverflow