PHP fclose() Function (original) (raw)

Last Updated : 31 May, 2025

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)

**Return Value:

**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 `

`

**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:

Best Practices for fclose()

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.