PHP File Read/Write Tutorial:
Writing to a File?
In PHP before you can write to a file you have to open the file, then you can write to the file.
To open a file in php is quiet simple
<?php
$myFile = "writeFile.txt";
$fh = fopen($myFile, 'w');
?>
'w' denotes that we want to open the file in write mode.
The fwrite function in php allows data to be written to any type of file. fwrite requires two pieces of information
(A) a file handle and (B) The information that is to be wrote to the file.
So now lets see an example:
<?php
$myFile = "writeFile.txt";
$fh = fopen($myFile, 'w');
$Data = "Hello World\n";
fwrite($fh, $Data);
fclose($fh);
?>
The $fh variable contains the file handle for testFile.txt. The file handle knows the current file pointer, which for writing, starts out at the beginning of the file.
After finishing writing Hello World to our file we have to close the file, passing it the file handle.
fclose($fh);