How to delete files inside a folder

Asked

Viewed 10,317 times

7

I want to delete all files and subfolders inside a folder, but without deleting it using PHP.

How can I do that?

  • 1

    (if Unix) see command rm

4 answers

6


Here is a ready-made function, posted on the PHP website

<?php 
/** 
* Recursively delete a directory 
* 
* @param string $dir Nome do diretório 
* @param boolean $deleteRootToo Ponha True se quiser deletar a pasta (nao é seu caso) 
*/ 
function unlinkRecursive($dir, $deleteRootToo) 
{ 
    if(!$dh = @opendir($dir)) 
    { 
        return; 
    } 
    while (false !== ($obj = readdir($dh))) 
    { 
        if($obj == '.' || $obj == '..') 
        { 
            continue; 
        } 

        if (!@unlink($dir . '/' . $obj)) 
        { 
            unlinkRecursive($dir.'/'.$obj, true); 
        } 
    } 
    closedir($dh); 
    if ($deleteRootToo) 
    { 
        @rmdir($dir); 
    } 
    return; 
} 
?>

Author: Jon Hassall

To use the function in your code, simply add a line calling the function, thus:

unlinkRecursive( '/www/luis/public_html/pasta_a_apagar', false );


The important point to note is the use of the deletion (@) in the unlink. She’s relevant in this case, because if we switch to file_exists, script may fail if more than one process is deleting files in folder.

6

PHP 5 or higher

To eliminate everything within a certain board:

$dir = "caminho/para/diretoria";
$di = new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS);
$ri = new RecursiveIteratorIterator($di, RecursiveIteratorIterator::CHILD_FIRST);

foreach ( $ri as $file ) {
    $file->isDir() ?  rmdir($file) : unlink($file);
}

Learn more about the classes Recursivedirectoryiterator and Recursiveiteratoriterator.


Checks

We should always take into account some details to garanth a correct functioning of the application. Among the same check:

  • If the path provided points to a board

    Verification can be performed quickly with the function is_dir():

    $dir = "caminho/para/diretoria";
    
    if (is_dir($dir)) {
      // é uma diretoria
    }
    else {
      // não é uma diretoria
    }
    
  • If the board is not empty

    We can verify using the method valid() iterator:

    $dir = "caminho/para/diretoria";
    
    $iterator = new \FilesystemIterator($dir);
    
    if ($iterator->valid()) {
      // tem coisas lá dentro
    }
    else {
      // vazio, não é preciso fazer nada
    }
    

Example

A complete example would be:

/**
 * Apagar Tudo
 * 
 * Remove todos os ficheiros, sub-diretorias e seus ficheiros
 * de dentro do caminho fornecido.
 * 
 * @param string $dir Caminho completo para diretoria a esvaziar.
 */
function apagarTudo ($dir) {

    if (is_dir($dir)) {

        $iterator = new \FilesystemIterator($dir);

        if ($iterator->valid()) {

            $di = new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS);
            $ri = new RecursiveIteratorIterator($di, RecursiveIteratorIterator::CHILD_FIRST);

            foreach ( $ri as $file ) {

                $file->isDir() ?  rmdir($file) : unlink($file);
            }
        }
    }
}

apagarTudo("caminho/para/diretoria");

0

I ended up solving my problem with the following code:

<?php
/* Crie uma nome da pasta exemplo: "nome_da_pasta" coloque arquivos dentro,
 * ele vai remover tudo como mostra o script abaixo
 */

/**
 * remover a pasta e tudo centro dele
 */
function ApagaDir($dir) {
  if($objs = glob($dir."/*")){
    foreach($objs as $obj) {
      is_dir($obj)? ApagaDir($obj) : unlink($obj);
    }
  }
  rmdir($dir);
} 

$nome_da_pasta="../public_html";

ApagaDir($nome_da_pasta); 

mkdir("../public_html");
?>
  • 1

    I edited it to improve the reading of the answer. You said in the question that you did not want to remove the folder itself, however your solution does that ?!? If you want to change to not remove the folder, then avoid creating it, just remove it from the function ApagaDir() the last line where it reads rmdir($dir);. So the folder itself is not removed and you no longer need the mkdir("../public_html");

-1

What is a php folder? If we’re on Unix, I suggest:

rm -rf nome_da_pasta/*

Very careful with folder removal experiments recursively! (This applies to all responses, of course).

  • With rm -rf If you get the wrong way, you’ll erase a lot. It’s not much healthy use it the way you describe it in the reply! At least complete it with a check!

  • @Zuul, of course! is the order (hence my warning)! all the answers presented are mercilessly erasing! :)

  • It’s solved ;) Thank you all very much.

Browser other questions tagged

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