Create a File
The
fopen function needs two important pieces of information to operate correctly. First,
we must supply it with the name of the file that we want it to open. Secondly, we must tell the function
what we plan on doing with that file (i.e. read from the file, write information, etc).
Since we want to create a file, we must supply a file name and tell PHP that we want to write
to the file. Note: We have to tell PHP we are writing to the file, otherwise it will not create a new file.
PHP Code:
$ourFileName = "testfile.txt";
$ourFileHandle = fopen($ourFileName, 'w') or die("can't open file");
fclose($ourFileHandle);
The file "testfile.txt" should be created in the same directory where
this PHP code resides. PHP will see that
"testFile.txt" does not exist and will create it after running this
code. There's a lot of information in those three lines of code, let's
make sure you understand it.
- $ourFileName = "testfile.txt";
Here we create the name of our file, "testfile.txt" and store it into a PHP String variable $ourFileName.
- $ourFileHandle = fopen($ourFileName, 'w') or die("can't open file");
This bit of code actually has two parts. First we use the function fopen and give it two arguments: our file name and we inform
PHP that we want to write by passing the character "w".
Second, 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 $ourFileHandle variable. We will talk more about file handles later on.
- fclose($ourFileHandle);
We close the file that was opened. fclose takes the file handle that is to be closed. We will talk more about this more in the file closing lesson.