How to open textfile and write to it append-style with php?

Chris_45 picture Chris_45 · Mar 15, 2010 · Viewed 40.8k times · Source

How do you open a textfile and write to it with php appendstyle

    textFile.txt

        //caught these variables
        $var1 = $_POST['string1'];
        $var2 = $_POST['string2'];
        $var3 = $_POST['string3'];

    $handle = fopen("textFile.txt", "w");
    fwrite = ("%s %s %s\n", $var1, $var2, $var3, handle);//not the way to append to textfile
fclose($handle);

Answer

Gumbo picture Gumbo · Mar 15, 2010

To append data to a file you would need to open the file in the append mode (see fopen):

  • 'a'
    Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it.
  • 'a+'
    Open for reading and writing; place the file pointer at the end of the file. If the file does not exist, attempt to create it.

So to open the textFile.txt in write only append mode:

fopen("textFile.txt", "a")

But you can also use the simpler function file_put_contents that combines fopen, fwrite and fclose in one function:

$data = sprintf("%s %s %s\n", $var1, $var2, $var3);
file_put_contents('textFile.txt', $data, FILE_APPEND);