Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท Files and I/O

PHP fclose() function

Reference for PHP fclose(): close an open file or stream handle, why closing flushes buffered data, the boolean result and what happens if you forget it.

fclose() closes a file handle that was opened with fopen() (or another stream function). Closing flushes any data still waiting in PHP's write buffer to the file and releases the operating-system handle so that other code can open, lock or delete the file.

PHP closes all open handles when the script ends, so forgetting fclose() rarely breaks a short script. In a long-running process, or when you reopen the same file straight away, an explicit close matters.

PHP
$handle = fopen("log.txt", "a");
fwrite($handle, "started\n");
fclose($handle);

Try it

PHP Close, then use the handle

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

PHP Closing in a finally block

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Syntax

PHP
fclose(resource $stream): bool
Name Description
$stream A handle returned by fopen(), fsockopen(), tmpfile() and similar functions.

Return value: true on success, false on failure (for example when flushing the final data fails).

Errors: in PHP 8, passing an already closed handle throws a TypeError, not a warning.

Usage notes

  • Closing flushes. Data written with fwrite() may sit in a buffer; fclose() guarantees it is handed to the operating system.
  • Do not use a handle after closing it. In PHP 8 the variable still holds a closed resource and any later call throws TypeError.
  • Close before deleting on Windows. An open handle can block unlink() and rename().
  • Use finally when an exception could skip the close, so the handle is released on every path.
  • Locks end with the handle. A lock taken with flock() is released by fclose().
  • Check the result when the data matters: a full disk can make the final flush fail, and fclose() then returns false.
  • Not for directory handles. Use closedir() for handles from opendir().
  • file_get_contents() and file_put_contents() open and close the file for you.