PHP Terms Files Text Append

 

- Info:

- This tutorial shows how to use PHP to append text to an existing file or to create new file if such file doesn't exist.

- If file exists data is appended to the end of the file.

- If file doesn't exists new one is created.

- File pointer is at the end of the file.

- Function file_put_contents() is identical to calling fopen(), fwrite() and fclose() to write data to a file.

- This tutorial is based on http://php.net/manual/en/function.file-put-contents.php.

 

- Simple:

- Create PHP Console Application Test.php

 

Test.php

<?php

file_put_contents('people.txt', "First line\n", FILE_APPEND | LOCK_EX); //Append content.

?>

 

- Complex:

- Create PHP Console Application Test.php

 

Test.php

<?php

$fp = fopen("test.txt", 'a'); //Create FilePointer for writing to file.

if($fp==false) {

print("Unable to open or create file.");

exit(1);

}

flock ($fp, LOCK_EX);

fwrite($fp, "Third line.\n");

flock ($fp, LOCK_UN);

fclose($fp);

?>

 

test.txt

First line.

Second line.

Third line.

 

test.txt (ASCII View)

46 69 72 73 74 20 6C 69 6E 65 2E 0A

53 65 63 6F 6E 64 20 6C 69 6E 65 2E 0A

54 68 69 72 64 20 6C 69 6E 65 2E 0A