How to Create a File Using PHP
To create a file using PHP, you need to use the fopen() function.
The fopen() function takes two parameters: the file name and the reason for opening that file.
For example, to create a file named "pat.txt" in order to write data into it, use this command
php$filename = "pat.txt";
$patfile = fopen($filename, 'w');
In the above code, we create the file "pat.txt" and then close the open file using the fclose() command.
The fopen() command returns a file handle which you can then use to manipulate the file to edit, delete and modify it.
The fclose() command closes the file using that file handle. After you have finished working with a file, you should always close it.
Besides creating a file, the fopen() command is also used to open already existing files. To open a file, you need to specify a mode: read, write or append, depending on what you are opening the file for.
The syntax to open an existing file is
$filehandle = fopen($filename, 'mode');
Types of File Modes
r: Open the file for read-only. File Pointer at the start of file.
w: Open the file for write only. File Pointer at the start of the file.
a: Open the file to append text at the end. File pointer at the end of the file.
Similarly, r+ can be used to both read and write from the file, w+ is the same as r+ but all the data is deleted when the file is opened. a+ is like r+ but the data isn't deleted, and the pointer is at the end of the file.
For example, to open the pat.txt file for appending data to it,
$patfile = fopen("pat.txt", 'a');