PHP - Is it possible to test the array_map('unlink', glob('/folder/my_files--*.txt')) command by try/catch?

I would like to test if the function array_map('unlink', glob('...*.txt')) did not encounter an error: ex.:

try { 
  array_map('unlink', glob('/folder/my_files--*.txt'));
} 
catch (\Exception $e) {
  echo 'Caught exception: ',  $e->getMessage(), "\n";
}

In your opinion, does this code seem valid? Thank you for your feedback !

Upvotes: 0

Views: 83

Answers (3)

lukas.j
lukas.j

Reputation: 7172

One could return the filenames where the unlinking failed with array_filter:

$filesNotDeleted = array_filter(glob('...'), 'unlink');

if (count($filesNotDeleted) === 0) {
  echo "Everything got deleted";
} else {
  echo "The following files were not deleted:";
  print_r($filesNotDeleted);
}

Upvotes: 1

Mmm!, in fact I'm too stupid, it doesn't matter the extension of the file, what I want is to empty the folder... Deceze's answer is very good if we want to specifically delete a type of file, among others other file types. I'm going to use DirectoryIterator:

$iterator = new DirectoryIterator(dirname(__FILE__));
foreach ($iterator as $fileinfo) {
    if (!$fileinfo->isDot()) {
        unlink( $fileinfo->getFilename() );
    }
}

Thank you for your answers, it's late here, it helped me think!

Upvotes: 0

deceze
deceze

Reputation: 522597

No, none of these function throw an exception, so no exception will ever be caught by this code. unlink returns true or false, so the result of array_map will be an array of true and/or false values, and you need to test whether all values in the array are true to know whether all unlink operations succeeded.

For this kind of operation, array_reduce is actually the better option, as it allows you to reduce the result to a single value right while you're iterating:

$result = array_reduce(glob('...'), fn($res, $file) => unlink($file) && $res, true);

if (!$result) {
    echo "Something didn't get deleted!";
}

Upvotes: 2

Related Questions