The fclose Function

The fclose function closes an open file descriptor, freeing system resources. It takes a file handle parameter that was previously obtained using the fopen function. The function returns true on successfully closing the file and false on error.

Syntax

phpfclose(resource $handle): bool

Example

Let's open a file for writing, write data to it, and close it:

php<?php
  $file = fopen('test.txt', 'w');
  fwrite($file, 'Hello World');
  $res = fclose($file);
  var_dump($res);
?>

Code execution result:

phptrue

Example

Let's try to close a non-existent descriptor:

php<?php
  $res = fclose(null);
  var_dump($res);
?>

Code execution result:

phpfalse

Example

Let's handle an exceptional situation:

php<?php
  $file = fopen('data.txt', 'w');
  
  try {
    fwrite($file, 'data');
  } finally {
    fclose($file);
  }
?>

See Also

  • the fopen function,
    which opens a file
  • the feof function,
    which checks for the end of a file
  • the flock function,
    which locks a file