Deleting files inside a folder

5

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

How can I do this?

    
asked by anonymous 29.03.2015 / 23:47

4 answers

4

Here's a ready function posted on the PHP site

<?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 by calling the function, like this:

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


The important point to note is the use of suppression ( @ ) in unlink . It is relevant in this case, because if we change to file_exists , the script can fail if more than one process is deleting files in the folder.

    
29.03.2015 / 23:59
6

PHP 5 or higher

To eliminate everything within a certain directory:

$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 RecursiveDirectoryIterator classes and RecursiveIteratorIterator .

Checks

We must always keep in mind some details to ensure correct operation of the application. Among these check:

  • If the path provided points to a directory

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

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

    We can check using the valid() method of the 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");
    
30.03.2015 / 00:00
0

I finally solved 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");
?>
    
30.03.2015 / 04:13
0

What is a php folder? If we are in unix, I suggest:

rm -rf nome_da_pasta/*

Very carefully with folder removal experiences recursively! (this applies to all the answers presented, of course).

    
30.03.2015 / 11:50