In the previous chapter, we learned how to read files. Now, we will learn how to create new files and write data to them using PHP. This is extremely useful for creating log files, generating reports, or saving user submissions.
Interestingly, the fopen() function is also used to create a file!
If you use fopen() on a file that does not exist, it will create it, given that the file is opened for writing (w) or appending (a).
$myfile = fopen("testfile.txt", "w");
The fwrite() function is used to write to a file.
The first parameter of fwrite() contains the name of the file pointer to write to, and the second parameter is the string that will be written.
<?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);
echo "Data successfully written!";
?>
If you open a file using the "w" (Write) mode, all existing data will be erased and replaced with the new data.
If you want to keep the existing data and simply add new text to the end of the file, you must use the "a" (Append) mode!
If you want to add text to an existing file without deleting its current contents, which mode should you use with fopen()?