294 of 410 menu

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

fclose(resource $handle): bool

Example

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

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

Code execution result:

true

Example

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

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

Code execution result:

false

Example

Let's handle an exceptional situation:

<?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
byenru