I have a list of file paths that I want to delete. I placed the file paths in a plaintext file in the root directory of the server. For example:
files_to_be_removed.txt
/path/to/bad/file.php
/path/to/another/bad/file.php
In the same directory, I have another file:
remove.php
$handle = @fopen("files_to_be_removed.txt", "r");
if ($handle) {
while (($buffer = fgets($handle, 4096)) !== false) {
if (unlink($buffer))
echo $buffer . ' removed.';
}
fclose($handle);
}
When I run my script, nothing is output. Simply, the files in the list aren’t being deleted. Why is that?
$files = file('files_to_be_removed.txt', FILE_IGNORE_NEW_LINES);
foreach ($files as $file) {
if (@unlink($file)) {
echo $file, ' removed', PHP_EOL;
} else {
$error = error_get_last();
echo 'Couldn\'t remove ', $file, ': ', $error['message'], PHP_EOL;
}
}
I'm guessing files are not being deleted because "you already have a LOCK on it" [just a guess] -- since you open it and check it's content.
You can avoid all the stress and simply adjust your entire script to a few lines:
foreach($filepaths as $filepath){
$status = @unlink($filepath);
#the @ is there for error suppression -- in case the file doesn't exist
if($status){
#do what you want -- it was successful
}
}