CodeBlanks Logo Icon CodeBlanks

Closing files with fclose()

PHP course · Intermediate · Lesson 74/115

Learn to close the file handle with fclose() and manage resources.

Closing files with fclose()

After you open a file with fopen(), you close the handle with fclose() when you are done. This flushes the written data to disk and releases the system resources.

For example, fclose($handle); closes the handle. It returns true on success and false on failure.

PHP automatically closes all open handles when the script ends. Still, closing the handle yourself is a good habit; it prevents resource leaks, especially in long-running scripts.

Resource management and leak prevention

An open handle holds an operating system resource in the background. If you open many files without closing them, the server may hit its concurrent handle limit and new openings will fail.

The typical pattern is: open with fopen, work with fwrite or fread, then close with fclose. This order ensures that data is safely written to disk and that no resources leak.

Following this order is especially important in large log files or scripts that open files inside a loop.

Exercise Open, write, close

Open data.txt with fopen() in 'w' mode and assign the handle to $handle. Use fwrite() to write a string. Then close the handle with fclose(). Finally print a short message with echo.

Show example solution
Write fwrite($handle, 'Done'); fclose($handle); echo 'Closed'; in order.
Example solution:
<?php
// Open the file in write mode
$handle = fopen(__DIR__ . '/data.txt', 'w');

// Write 'Done'
fwrite($handle, 'Done');

// Close the handle
fclose($handle);

// Print the message
echo 'Closed';

Test yourself

  1. Why should you close a handle opened with fopen?

    • PHP errors and the script stops if you do not
    • Without fclose the file is deleted
    • Closing is only required in read mode, not in write mode
    • fwrite data is flushed to disk and system resources are released
    Show answer

    fwrite data is flushed to disk and system resources are released — Correct. fclose flushes writes to disk and releases the resources held by the handle.

  2. Close the handle

    $closed = fclose(____);
    Show answer
    $closed = fclose($handle);
  3. Match fclose and resource concepts

    fclose()
    Closes the handle
    true return
    Close succeeded
    Open handle
    Holds a resource
    Script end
    PHP auto-closes

All lessons in Intermediate