Delete folder and contents with php

Asked

Viewed 3,418 times

0

Good guys want to delete a folder from my site with php, and want to delete all files and sub-folders.

I’m using the following command:

unlink("Arquivos/$token"); 

Is that correct? It erases all files and sub-folders?

This is giving the following error:

Warning: unlink(Arquivos/5b6a7a075e26664fd69e23f60c5d55bc): Operation not permitted in /Library/WebServer/Documents/Sites/Sistema/Paginas/Servidor/Todos_Clientes.php on line 90
  • No, the unlink delete only one file, to delete the directory use the rmdir.

  • 1

    To delete a folder is rmdir(), however, the folder must be empty. To resolve you need to create a recursion and checking what file you use unlink(), whatever folder, use rmdir().

1 answer

4


You can use this PHP function that erases the folder and its internal files:

    function delTree($dir) { 
      $files = array_diff(scandir($dir), array('.','..')); 
      foreach ($files as $file) { 
        (is_dir("$dir/$file")) ? delTree("$dir/$file") : unlink("$dir/$file"); 
      } 
      return rmdir($dir); 
    }

    delTree('caminho/da/pasta/aqui');

That function is in itself php manual

I hope I’ve helped.

  • and how I have the return true or false of this function?

  • true or false?... would be to confirm that you actually deleted?

  • 1

    simply assign the function to a control variable. $ok = delTree('my/folder'); . You can use the function together is_dir to check if there really is that file/folder that you want to delete.

  • Very good, it worked 100%, thank you

Browser other questions tagged

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