Reading and Writing Files
By Peter McNulty : 08-01-2005
Writing to Files
It is natural in ones life to wonder, 'how do I write to a file using PHP?' Well, here's how! In fact we are actually going to append to the file. This means that we are going to write to the end of the file, to add more content. If we were to just plain write to the file, everything would first be automatically erased and this is not so useful to us.
We need to create a form to allow new sayings to be added, and combine this with the required PHP code:
This example code is a full script for adding sayings to the randomsayings.txt text file. It incorporates a form, error checking and the appropriate code to add the sayings. In order to append the file (write at the end of the file), we first have to open the file using append mode or the a character. Like usual, we use the binary modifier to avoid incompatibilities. To write, we use fwrite() which takes two parameters; the file resource, and the data to be written to the file.
The above code produces something along the lines of this:
As you can see, it is not too difficult to write to the end of a file. It is though much more difficult to write to the middle of a file or to edit lines that already exists in a file – this is out of the scope of this article. If you wanted to clear a file and write to the beginning, all you have to do is use the write mode wb. Hopefully, this short introduction helps you understand the basics of reading and writing to files in PHP.
<< Page 3 of 3