views:

67

answers:

2

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);
+1  A: 

You could use the a option instead of w. This manual page shows the options to fopen.

Adriano Varoli Piazza
Why the downmod?
Adriano Varoli Piazza
+3  A: 

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);
Gumbo
+1 for going into detail. `fprintf()` would also be a good choice.
Frank Farmer