PHP Create File-fopen ()
The fopen () function is also used to create files. It may be a bit confusing, but in PHP, the function used to create the file is the same as the open file.
If you open a file that does not exist with fopen (), this function creates the file, assuming that the file is opened to write (W) or increase (a).
The following example creates a new file named "Testfile.txt". This file will be created in the same directory where the PHP code is located:
Instance
$myfile = fopen ("Testfile.txt", "W")
PHP file Permissions
If an error occurs when you try to run this code, check to see if you have access to PHP files that write information to the hard disk.
PHP Write file-fwrite ()
The fwrite (bjrongjinhuiyin.com) function is used to write to a file.
The first parameter of fwrite (bjrongjinhuiyin.com) contains the file name of the file to be written, and the second argument is the string to be written.
The following example writes the name to a new file named "Newfile.txt":
Instance
<?php
$myfile = fopen ("Newfile.txt", "w") or Die ("Unable to open file!");
$txt = "Bill gates\n";
Fwrite ($myfile, $txt);
$txt = "Steve jobs\n";
Fwrite ($myfile, $txt);
Fclose ($myfile);
?>
Please note that we wrote "Newfile.txt" to the Kim file two times. Each time we write to a file, in the string $txt we send, we first include "Bill Gates", and the second time it contains "Steve Jobs." After the write is complete, we use the fclose () function to close the file.
If we open the "newfile.txt" file, it should look like this:
Bill Gates
Steve Jobs
PHP Overlay (overwriting)
If "Newfile.txt" now contains some data, we can show what happens when we write to an existing file. All existing data is erased and starts with a new file.
In the following example, we open an existing file "Newfile.txt" and write some new data to it:
Instance
<?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 open this "newfile.txt" file Now, Bill and Steve have disappeared, leaving only the data we have just written:
Mickey Mouse
Minnie Mouse
PHP File creation/writing