What is fclose() in PHP?
The fclose() function is used to close an open file pointer in PHP.
- When you open a file using
fopen(), PHP keeps a connection to that file.
- After you are done working with the file (reading, writing, etc.), you should close it using
fclose() to free up system resources.
Syntax
fclose(resource $stream): bool
$stream: This is the file pointer resource (the variable returned by fopen()).
- It returns:
true if the file is successfully closed.
false if an error occurs.
Simple Example
<?php
// Open a file for reading
$file = fopen("example.txt", "r");
if ($file) {
// Read the first line
echo fgets($file);
// Close the file
fclose($file);
} else {
echo "Unable to open file!";
}
?>
Explanation:
fopen("example.txt", "r") opens the file in read mode.
fgets($file) reads a line.
fclose($file) closes the file after reading.
Why is fclose() important?
- Prevents memory leaks.
- Releases the lock on a file (important if many users/programs are accessing the same file).
- Good practice: Always close a file after finishing work with it.
Another Example with Writing
<?php
// Open a file for writing
$file = fopen("sample.txt", "w");
if ($file) {
fwrite($file, "Hello, world!");
// Important to close the file after writing
fclose($file);
echo "Data written and file closed successfully.";
} else {
echo "Unable to open file!";
}
?>
Here, after writing "Hello, world!" into sample.txt, we close the file using fclose().
What happens if you don't use fclose()?
- PHP usually automatically closes files at the end of the script.
- But manually closing with
fclose() is safer and more reliable, especially in large scripts or when handling multiple files.