phpfile-handlingfclose

Close all the opened files at once in php


Is there any way to close all the files that are open in the program without using fclose() for each file separately?

Something like this-

$txt_template1 = fopen("1.txt", "r") or die("Unable to open file!");
$txt_template2 = fopen("2.txt", "r") or die("Unable to open file!");
$txt_template3 = fopen("3.txt", "r") or die("Unable to open file!");
$txt_template4 = fopen("4.txt", "r") or die("Unable to open file!");
$txt_template5 = fopen("5.txt", "r") or die("Unable to open file!");
$txt_template6 = fopen("6.txt", "r") or die("Unable to open file!");

fclose(ALL_OPEN_FILES);

Solution

  • get_resources() is a function in PHP7 that returns an array of all currently active resources.

    For an array of all opened files, use it with the filter 'stream' - get_resources('stream')

    Map the returned array with the function fclose()

    array_map('fclose', get_resources('stream'))

    This will close all the open files.