PHP Close File

To close a file in PHP, we use a very simple function called the fclose function. The fclose function simply closes the file which is indicated by the file pointer which is passed to it.

You should always close files when you are finished with them to free resources. Some operating systems require that a file be closed before it can be deleted, so if you forgot to close a file, you may have trouble deleting it.

Have a look at the tutorial below which explains how to properly close a file in PHP using the PHP close file function.

PHP fclose Syntax

The PHP fclose function, which is used to close a file, has the following syntax:

fclose($fileHandle);

$fileHandle is the handle that was created when the file was opened.

PHP fclose Example - Closing a file in PHP

The following example writes a line to the file "test.txt" and then closes it. Look at the code and you can easily see how it works.

<?php
 
$file = "test.txt";
$fileHandle = fopen($file, 'w') or die("Error opening file");
 
$data = "Tutorial Arena rocks\n"; // set data we will be writing
fwrite($fileHandle, $data); // write data to file 
 
fclose($fileHandle); // close the file since we're done
 
?>

As we said earlier, you only need to pass the file handle to this function and it will take care of the rest. It is a pretty simple concept to understand with regards to closing a file in PHP.

For more examples of using PHP to close a file using fclose, take a look at our PHP writefile tutorial.

The PHP close file function, fclose, is very simple as we saw above. Remember always to close files when you are finished working with them. This advice is not limited to PHP, but when working with any file in general.

We hope this tutorial was helpful. Please move on to another tutorial in our series.

Link to this Page

Thank Tutorial Arena for This Tutorial.
Show your appreciation with a +1...