Home
 
 
Search:  
C C++ Perl PHP Python HTML ShellScripts
 
 
  Coding Books
  Tutorials
  Search Code
  Browse Code
  Link to Us
  Site News
  Contact Metalshell
 
 
 
  Submit Code   Statistics
 



Beginning PHP4    (ISBN: 1861003730)


 

 List Price: $39.99
 Our Price: $27.99
 Used Price: $27.75

 Release Date: October, 2000
 Manufacturer: Wrox Press Inc (Perfect Paperback)
 Sales Rank: 5,315

 Author: Chris Lea, Wankyu Choi, Allan Kent, Ganesh Prasad, Chris Ullman









More Info

 Write Files 2003-02-17 00:21:09
  php 
Category: source:php:files
Description: Write and append to a file using fwrite.
Platform: all
Author: detour
Viewed: 7010
Rating: 4.2/5 (31 votes)
If you have any questions about this piece of code or still need help, try posting your question on the forum.

 

Printable Version
writefile.php
<?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;
  }
?>
Rate this code:
(Not Helpful)  (Very Helpful) 

 
 
   Developer.*  
   Blue Parrots  
   Technipal  
   Defy Magazine  
   Code Project  
   Prog. Heaven  


Got Money?