Category Archives: PHP-fopen() and fclose()

PHP-fopen() and fclose()

This function creates the file if the file doesn’t exists . The fopen function needs two important pieces of information to operate correctly.
1. we must supply it with the name of the file that we want it to open.
2. we must tell the function what we plan on doing with that file (i.e. read from the file, write information, etc).
Example Code:
$fileName = “filename.txt”;
$fileHandle = fopen($fileName, ‘w’) or die(“can’t open file”);

• $fileName = “filename.txt”;
Here we create the name of our file, “filename.txt” and store it into a PHP String variable $fileName.
• $fileHandle = fopen($filnename, ‘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 $fileHandle variable. We will talk more about file handles later on.
• fclose($fileHandle);
We close the file that was opened. fclose takes the file handle that is to be closed.