Write Files
2003-02-17 00:21:09
Category: php:files
Description: Write and append to a file using fwrite.
Author: detour
Viewed: 7239
Rating: (31 votes)


<?php
  // writefile.php by detour@metalshell.com
  //
  // Write to a file using fwrite.
  //
  // http://www.metalshell.com/
  //
 
  $outfile = "tmpfile";
 
  $writestring = "first line\nsecond line\nthird line\n";
  $appendstring = "fourth line\n";
 
  // Open file for writing, any data currently in the file will be lost.
  if(!$fd = fopen($outfile, "w")) {
    echo("Error opening file.");
    exit;
  }
 
  // Write the string to the file.
  if(!fwrite($fd, $writestring)) {
    echo("Error writing file.");
    exit;
  }
 
  fclose($fd);
 
  echo("The file now contains:<br>");
  print_file($outfile);
 
  // Open file for appending
  if(!$fd = fopen($outfile, "a")) {
    echo("Error opening file.");
    exit;
  }
 
  // Append the string to the file.
  if(!fwrite($fd, $appendstring)) {
    echo("Error writing file.");
    exit;
  }
 
  fclose($fd);
 
  echo("The file now contains:<br>");
  print_file($outfile);
 
 
 
  function print_file($file) {
    if(!$inf = fopen($file, "r"))
      return;
 
    $data = fread($inf, filesize($file));
 
    $data = ereg_replace("\n", "<br>", $data);
 
    echo $data;
  }
?>