Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

text-files

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);
like image 429
Chris_45 Avatar asked Mar 15 '10 16:03

Chris_45


1 Answers

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);
like image 117
Gumbo Avatar answered Oct 09 '22 17:10

Gumbo