PHP how to delete file . jpg from all possible folders and subfolders

Asked

Viewed 54 times

1

Currently I can easily delete files from a folder with the code below

array_map('unlink', glob($diretorio."*.jpg"));

However I cannot find a way to access possible subfolders, the names of the subfolders and their amount can be random and unpredictable, as I could create a loop to go through all possible paths and go deleting the desired files ?

  • I can do it effortlessly with the class Recursivedirectoryiterator. But I don’t know if using an iterator serves you.

  • On my website the user about a . zip, I do the unzipping, but I know it is possible to have inside the zip malicious files, or files that should not be there, With the array_map('unlink', glob($directory."*.jpg")); I hit jpg files only from the root folder, But I fear that users go up in zip sub folders and inside them imprudent files so to speak> I would need a way to go through all possible subfolders and go deleting files. jpg for example .

  • I found ways to scan the main folder, but I can’t figure out a way to access subfolders I don’t know the names of

  • It is also possible to delete directly in the zipped file, but I believe it is the case to ask another question.

1 answer

-1

Some concepts should be seen.

Recursive and non-rerecursive iterators

PHP has no iterators "recursive", as in ArrayIterator and FilesystemIterator. There are also "recursive" iterators, such as RecursiveArrayIteratore RecursiveDirectoryIterator. The latter have methods that allow them deepen, the first not.

When the instances of these iterators are executed in loop by own account, even recursives, values only come from the level "top" even if they are looped in an array or directory nestled with subdirectories.

Source: https://stackoverflow.com/a/12235779/11379709

$diretorio = '.';        //Caminho do diretório a ser vasculhado.

//Obtém um iterador não recursivo que lista caminho dos arquivos do diretório 
//assim como os arquivos de seus subdiretórios.
$IteratorRecursivo = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($diretorio)
);

//Filtra os arquivos com extensão .jpg e cria um array com o caminho desses arquivos.
$Arquivos = array_keys(
  iterator_to_array(
      new RegexIterator(
         $IteratorRecursivo, '/^.+\.jpg$/i',
         RegexIterator::GET_MATCH
      )
  )
);

//Exclui os arquivos .jpg do diretórios e de seus subdiretórios.
array_map("unlink", $Arquivos);
  • Who voted negative could help me and point out where the error is?

Browser other questions tagged

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