Deleting files from a PHP directory

Asked

Viewed 45 times

0

I have a directory with images and need that each time you start the program the images are deleted except one.

I have for now the following code:

    $dirtmp = "fotos/tmp";
    $ditmp = new RecursiveDirectoryIterator($dirtmp, FilesystemIterator::SKIP_DOTS);
    $ritmp = new RecursiveIteratorIterator($ditmp, RecursiveIteratorIterator::CHILD_FIRST);

    foreach ( $ritmp as $file ) {
           unlink($file);
    }

This causes you to delete all files, but would like the file zVazio.jpg was never deleted from that folder.

Is there any way to before excluding (unlink) verify the file name and if zVazio.jpg he does not exclude ?

2 answers

1

Can you guarantee that the name will always look like this? If so, just filter when you find the expected name in the file being considered. If you cannot guarantee this you may need to do some other operation like normalize everything to tiny.

This does not deal with certain problems, such as lack of permission.

There are other ways to get the name, but I thought this one fits. Just be careful because checking if the name is just that or if it is anywhere can give false positive.

$dirtmp = "fotos/tmp";
$ditmp = new RecursiveDirectoryIterator($dirtmp, FilesystemIterator::SKIP_DOTS);
$ritmp = new RecursiveIteratorIterator($ditmp, RecursiveIteratorIterator::CHILD_FIRST);
foreach ($ritmp as $file) if (!endsWith($file, "zVazio.jpg")) unlink($file);

function endsWith($haystack, $needle) {
    $length = strlen($needle);
    if ($length == 0) return true;
    return (substr($haystack, -$length) === $needle);
}

If you prefer you can do:

$dirtmp = "fotos/tmp";
$ditmp = new RecursiveDirectoryIterator($dirtmp, FilesystemIterator::SKIP_DOTS);
$ritmp = new RecursiveIteratorIterator($ditmp, RecursiveIteratorIterator::CHILD_FIRST);
foreach ($ritmp as $file) if ($file->getFilename() != "zVazio.jpg") unlink($file);

I put in the Github for future reference.

  • perfect... the file name will always be the same....

0

Checks whether the $file is coming correctly with the file name and makes a if:

if ('zVazio.jpg' === $file) {
    unlink($file);
}

If you are unsure of the file name/path, you can try using strpos to check if the file name is in the string $file:

if (strpos($file, 'zVazio.jpg') === false) {
    unlink($file);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.