Open In App

PHP fclose() Function

Last Updated : 31 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The fclose() function in PHP closes a file that was previously opened by fopen(). Closing a file releases the resource associated with it and makes sure all the data written to the file is properly saved. Not closing files can lead to resource leaks or incomplete data writing.

Syntax:

bool fclose(resource $handle)
  • $handle: The file resource you want to close. This is the value returned by fopen().

Return Value:

  • Returns true on success.
  • Returns false if the file pointer is invalid or the close operation fails.

Note: The fclose() function was originally introduced in core PHP 4 and continues to be fully supported in PHP 5, PHP 7, and PHP 8 versions.

Now, let us understand with the basic example of the fclose() function:

This code opens a file, writes some text, and then closes it properly.

PHP
<?php
// Open a file for writing
$file = fopen("example.txt", "w");
if ($file) {
    fwrite($file, "This is a sample text.");
    // Close the file after writing
    fclose($file);
    echo "File written and closed successfully.";
} else {
    echo "Failed to open the file.";
}
?>

Output:

Screenshot-2025-05-31-175132
PHP fclose() Function

What Happens If You Don’t Use fclose()?

If you don’t explicitly close a file, PHP will automatically close all open files at the end of script execution. However, relying on this automatic closure is not recommended because:

  • It can cause delays in freeing resources.
  • It may lead to data not being saved properly in long-running scripts.
  • In complex scripts, it’s better to close files as soon as you’re done with them.

Best Practices for fclose()

  • Always call fclose() after finishing working with a file.
  • Check the return value of fclose() to confirm the file closed properly.
  • Avoid using the file resource after closing it.
  • In case of multiple files open simultaneously, close each one as soon as you finish.
  • Use error handling around file operations for robust code.

Conclusion

The fclose() function is essential for properly closing files in PHP. It releases resources, and prevents resource leaks. While PHP closes open files automatically at the end of the script, explicitly closing files with fclose() is a good practice for better control and efficiency.


Next Article
Practice Tags :

Similar Reads