Let's say I do fopen('filename.ext', 'w');
, but I didn't store the handle. Next I need to delete that file. Is there a way to find that this file has a handle attached to it and next close that unnamed handle ?
From the docs:
Thanks to the reference-counting system introduced with PHP 4's Zend Engine, a resource with no more references to it is detected automatically, and it is freed by the garbage collector. For this reason, it is rarely necessary to free the memory manually.
On Linux, you can list /proc/self/fd/
to get the handles and corresponding file names, but there's no platform-independent php function.
Instead of wildly closing handles, you should wrap the fopen
calls in try .. finally blocks (php 5.3+):
$f = fopen('filename.ext', 'w');
if ($f !== false) {
try {
// Some code that may throw an exception
} finally {
fclose($f);
}
}
Note that at least on POSIX systems, you can also just delete the file (name) while you're holding a handle to it.