Open and Write a File

  • Opening a file uses ‘w’ to overwrite, ‘a’ to append, ‘r’ to read.
  • Opens a file, clears the file, writes stringData then closes file.
$myFile = "testfile.txt";
$fh = fopen($myFile, 'w') or die("cannot open file");
$stringData = "Bobby Bopper\n";
fwrite($fh, $stringData);
fclose($fh);

File Reading

$myFile = "testfile.txt";
$fh = fopen($myFile, 'r');
  • Read 5 number of chars $theData = fread($fh, 5);
  • Read whole file $theData = fread($fh, filesize($myFile));
  • Read 1 line $theData = fgets($fh);
" "