After my script finishes I can delete the file, but while it's running I can't touch it, even after an fclose()
. Here is the code I'm trying to use:
$Files = glob("$_SERVER[DOCUMENT_ROOT]/files/*.csv");
$File = fopen($Files[0], "r");
//while (($Data = fgetcsv($File)) !== false) {...
$i = 0;
while (is_resource($File)) {
$i && sleep(1);
echo "Closing handle.\n";
fclose($File);
if (++$i > 5)
die("Could not close handle.");
}
foreach ($Files as $File) {
$i = 0;
while (file_exists($File)) {
$i && sleep(1);
echo "Deleting file.\n";
@unlink($File);
echo 'www-data@debian:~$ ', $Command = "rm -f '$File' 2>&1", "\n", shell_exec($Command);
if (++$i > 5)
die("Could not delete the file.");
}
}
As you can see I'm trying to delete it through unlink()
and using shell commands and neither are working, both give me this error:
rm: cannot remove 'invincible-file.csv': Text file busy
I also realize the script might be a bit overkill, but that's purely because I couldn't get it to work in any way, and some of the extra code is just for output purposes to try and debug what is happening.
filesystems that you can unlink a file that is open. It simply removes the directory entry. The file is still available to a process that holds it open as long as it is open. Once closed the inode is destroyed.
PHP | unlink() Function The unlink() function is an inbuilt function in PHP which is used to delete files. It is similar to UNIX unlink() function. The $filename is sent as a parameter that needs to be deleted and the function returns True on success and false on failure. Syntax: unlink( $filename, $context )
Unlink() function: The unlink() function is an inbuilt function in PHP which is used to delete a file. The filename of the file which has to be deleted is sent as a parameter and the function returns True on success and False on failure.
To delete a file in PHP, use the unlink function. Let's go through an example to see how it works. The first argument of the unlink function is a filename which you want to delete. The unlink function returns either TRUE or FALSE , depending on whether the delete operation was successful.
I've run into this issue before and been able to remedy by forcing garbage collection after closing the file and before unlinking it:
gc_collect_cycles();
By far not the best solution, but it did resolve an issue I had deleting files that had been previously opened and closed lines before.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With