In PHP, fclose() closes a file that was opened with fopen(). It tells PHP you are finished with the file so it can free the resource and finish writing any saved data.
PHP closes open files automatically when the script ends, but closing them yourself is a good habit. It frees memory sooner and releases file locks, which matters in long scripts that open many files.
Syntax
Call fclose() with the values you need. Start with this line.
PHP
fclose($handle);
Call
What it does
fclose($handle)
Closes the file handle and returns true or false.
fclose(fopen(__DIR__ . "/demo.txt", "w"))
Creates an empty file by opening and closing it right away.
if (is_resource($handle)) { fclose($handle); }
Closes the handle only if it is still open.
fclose() works on any stream opened by fopen(), fsockopen(), or popen(). Since PHP 8, using a handle after fclose() throws a TypeError instead of only giving a warning.
Library declarations
PHP
fclose(resource $stream): bool
Parameters
Parameter
Description
stream
Required. The file pointer returned by fopen() or a similar function.
Return Value
Return Value
Description
bool
true on success, false on failure.
PHP Examples
Example 1 — Write to a File and Close It
Open a file for writing, add some text, then close it with fclose().