Is it possible to do "if file exists then append, else create new file" shorter than this

if (file_exists($myFile)) {
  $fh = fopen($myFile, 'a');
  fwrite($fh, $message."\n");
} else {
  $fh = fopen($myFile, 'w');
  fwrite($fh, $message."\n");
}
fclose($fh);

==

if (file_exists($myFile)) {
  $fh = fopen($myFile, 'a');
} else {
  $fh = fopen($myFile, 'w');
} 
fwrite($fh, $message."\n");
fclose($fh);

==

$fh = fopen($myFile, (file_exists($myFile)) ? 'a' : 'w');
fwrite($fh, $message."\n");
fclose($fh);

== (because a checks if the file exists and creates it if not)

$fh = fopen($myFile, 'a');
fwrite($fh, $message."\n");
fclose($fh);

==

file_put_contents($myFile, $message."\n", FILE_APPEND);

...of course, file_put_contents() is only better if it is the only write you perform on a given handle. If you have any later calls to fwrite() on the same file handle, you're better going with @Pekka's answer.


Umm... why? a already does what you need out of the box.

Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it.


$method = (file_exists($myFile)) ? 'a' : 'w';
$fh = fopen($myFile,$method);
fwrite($fh, $message."\n");

Tags:

Php