Entry
How can I add/write to an existing file?
Feb 3rd, 2002 02:58
Philip Olson, jamie dyer, Colin Viebrock, Henrik Jönsson, Peter Morrissette, Nathan Wallace, http://www.php.net/manual/function.fopen.php
An important function to understand is fopen() which is defined as:
fopen -- Opens file or URL
http://www.php.net/fopen
It's important to read about fopen "modes" as mode is the second
parameter for this function. Since we're adding (appending) to a file,
we'll use mode 'a'. Mode 'a' is defined as:
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.
Now let's put it to use. First, let's define our filename:
$filename = '/home/example/foo.txt';
Let's open it, in mode 'a':
$fp = fopen($filename, 'a');
And now we'll write (append) to it:
fwrite($fp, "I will be appended to $filename \n");
So in summary:
<?php
$fp = fopen('somefile.txt', 'a');
if (!$fp) {
print "Error: Cannot open file ($filename)";
exit;
}
fwrite($fp, "I will be appended to $filename\n");
fclose($fp);
?>