fopen function is basically used to open files but it can also used for creating files in PHP. So if we use fopen function on a file that does not exist then it will create it otherwise it will open the existing file.
How to Create a File?
$myfile = "create.txt";
$myfilehandle = fopen($myfile, 'w') or die("can't open file");
Note: The file "create.txt" should be created in the same directory where this PHP code resides. PHP Interpreter will see that "create.txt" does not exist and will create it after running this code.
In the above example:
- $myfile = "create.txt"; this statement specifies that we create the name of our file, "create.txt" and store it into a PHP String variable $myfile.
- $myfilehandle = fopen($myfile, 'w') or die("can't open file"); this statement specifies that First of all we use the function fopen and give it two arguments: first one is the name of the file that is "$myfile" and the second one is the mode in which we want to open that file that is "w" (write mode).. Secondly, the fopen function returns what is called a file handle, which will allow us to manipulate the file. We save the file handle into the $myfilehandlevariable.
- close($myfilehandle); this statement close the opened file. fclose function takes the file handle that is to be closed.