The fopen()
function can also be used to create a file. This might be a bit confusing, but in PHP, file creation is handled by the same function used for opening files.
If you use fopen()
on a file that does not exist, it will create the file if it is opened in writing (w) or appending (a) mode.
The example below creates a new file named “testfile.txt,” which will be placed in the same directory as the PHP code.
$myfile = fopen(“testfile.txt”, “w”) |
If you encounter errors while running this code, ensure that your PHP file has the necessary permissions to write to the hard drive.
The fwrite()
function is used to write data to a file.
The first parameter of fwrite()
is the file handle where data will be written, and the second parameter is the string of data to be written.
The example below writes a few names into a new file named “newfile.txt”:
<?php $myfile = fopen(“newfile.txt”, “w”) or die(“Unable to open file!”); $txt = “John Doe\n”; fwrite($myfile, $txt); $txt = “Jane Doe\n”; fwrite($myfile, $txt); fclose($myfile); ?> |
Notice that we wrote to the file “newfile.txt” twice. Each time, we wrote the string $txt
, which first contained “John Doe” and then “Jane Doe”. After completing the writing process, we closed the file using the fclose()
function.
If you open the “newfile.txt” file, it would appear as follows:
John Doe Jane Doe |
Now that “newfile.txt” contains data, let’s demonstrate what happens when we open an existing file for writing. The existing data will be erased, and the file will start as empty.
In the example below, we open the existing file “newfile.txt” and write some new data into it:
<?php $myfile = fopen(“newfile.txt”, “w”) or die(“Unable to open file!”); $txt = “Mickey Mouse\n”; fwrite($myfile, $txt); $txt = “Minnie Mouse\n”; fwrite($myfile, $txt); fclose($myfile); ?> |
If we now open the “newfile.txt” file, we’ll find that both John and Jane have disappeared, and only the new data we just wrote remains.
Mickey Mouse Minnie Mouse |
You can append data to a file using the “a” mode. The “a” mode adds text to the end of the file, while the “w” mode overwrites and erases the existing content.
In the example below, we open the existing file “newfile.txt” and append some text to it:
<?php $myfile = fopen(“newfile.txt”, “a”) or die(“Unable to open file!”); $txt = “Donald Duck\n”; fwrite($myfile, $txt); $txt = “Goofy Goof\n”; fwrite($myfile, $txt); fclose($myfile); ?> |
If we now open the “newfile.txt” file, we’ll see that “Donald Duck” and “Goofy Goof” have been appended to the end of the file.
Mickey Mouse Minnie Mouse Donald Duck Goofy Goof |