Writing or Appending to a File

The processes for writing to and appending to a file are the same. The difference lies in the fopen() call. When you write to a file, you use the mode argument "w" when you call fopen():

$fp = fopen("test.txt", "w");

All subsequent writing occurs from the start of the file. If the file doesn't already exist, it is created. If the file already exists, any prior content is destroyed and replaced by the data you write.

When you append to a file, you use the mode argument "a" in your fopen() call:

$fp = fopen("test.txt", "a");

Any subsequent writes to your file are added to the existing content, but if you attempt to append content to a nonexistent file, the file is first created.

Writing to a File with fwrite() ...

Get Sams Teach Yourself PHP, MySQL® and Apache All in One now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.