PHP: Desvincular Todos Los Archivos Dentro De Un Directorio, y luego Eliminar Ese Directorio


¿Hay una manera de usar las búsquedas de expresiones regulares o comodines para eliminar rápidamente todos los archivos dentro de una carpeta, y luego eliminar esa carpeta en PHP, SIN usar el comando "exec"? Mi servidor no me da autorización para usar ese comando. Un simple bucle de algún tipo sería suficiente.

Necesito algo que logre la lógica detrás de la siguiente declaración, pero obviamente, sería válida:


$dir = "/home/dir"
unlink($dir . "/*"); # "*" being a match for all strings
rmdir($dir);

Author: NoodleOfDeath, 2012-06-29

8 answers

Uso glob para encontrar todos los archivos que coinciden con un patrón.

function recursiveRemoveDirectory($directory)
{
    foreach(glob("{$directory}/*") as $file)
    {
        if(is_dir($file)) { 
            recursiveRemoveDirectory($file);
        } else {
            unlink($file);
        }
    }
    rmdir($directory);
}
 75
Author: Lusitanian,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-04-10 22:01:56

Uso glob() para recorrer fácilmente el directorio para eliminar archivos, puede eliminar el directorio.

foreach (glob($dir."/*.*") as $filename) {
    if (is_file($filename)) {
        unlink($filename);
    }
}
rmdir($dir);
 16
Author: John Conde,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-11-04 16:36:35

El glob() la función hace lo que estás buscando. Si estás en PHP 5.3+ podrías hacer algo como esto:

$dir = ...
array_walk(glob($dir . '/*'), function ($fn) {
    if (is_file($fn))
        unlink($fn);
});
unlink($dir);
 9
Author: svens,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-06-29 18:36:12

Prueba la manera fácil:

$dir = "/home/dir";
array_map('unlink', glob($dir."/*"));
rmdir($dir);

En función para eliminar dir:

function unlinkr($dir, $pattern = "*") {
        // find all files and folders matching pattern
        $files = glob($dir . "/$pattern"); 
        //interate thorugh the files and folders
        foreach($files as $file){ 
            //if it is a directory then re-call unlinkr function to delete files inside this directory     
            if (is_dir($file) and !in_array($file, array('..', '.')))  {
                unlinkr($file, $pattern);
                //remove the directory itself
                rmdir($file);
                } else if(is_file($file) and ($file != __FILE__)) {
                // make sure you don't delete the current script
                unlink($file); 
            }
        }
        rmdir($dir);
    }

//call following way:
unlinkr("/home/dir");
 6
Author: Ahosan Karim Asik,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-10 10:47:18

Puede usar el componente Symfony Filesystem, para evitar reinventar la rueda, por lo que puede hacer

use Symfony\Component\Filesystem\Filesystem;

$filesystem = new Filesystem();

if ($filesystem->exists('/home/dir')) {
    $filesystem->remove('/home/dir');
}

Si prefiere administrar el código usted mismo, aquí está la base de código Symfony para los métodos relevantes

class MyFilesystem
{
    private function toIterator($files)
    {
        if (!$files instanceof \Traversable) {
            $files = new \ArrayObject(is_array($files) ? $files : array($files));
        }

        return $files;
    }

    public function remove($files)
    {
        $files = iterator_to_array($this->toIterator($files));
        $files = array_reverse($files);
        foreach ($files as $file) {
            if (!file_exists($file) && !is_link($file)) {
                continue;
            }

            if (is_dir($file) && !is_link($file)) {
                $this->remove(new \FilesystemIterator($file));

                if (true !== @rmdir($file)) {
                    throw new \Exception(sprintf('Failed to remove directory "%s".', $file), 0, null, $file);
                }
            } else {
                // https://bugs.php.net/bug.php?id=52176
                if ('\\' === DIRECTORY_SEPARATOR && is_dir($file)) {
                    if (true !== @rmdir($file)) {
                        throw new \Exception(sprintf('Failed to remove file "%s".', $file), 0, null, $file);
                    }
                } else {
                    if (true !== @unlink($file)) {
                        throw new \Exception(sprintf('Failed to remove file "%s".', $file), 0, null, $file);
                    }
                }
            }
        }
    }

    public function exists($files)
    {
        foreach ($this->toIterator($files) as $file) {
            if (!file_exists($file)) {
                return false;
            }
        }

        return true;
    }
}
 4
Author: Adam Elsodaney,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-01-09 14:07:41

Una forma simple y efectiva de eliminar todos los archivos y carpetas recursivamente con Biblioteca PHP estándar, para ser específicos, RecursiveIteratorIterator y RecursiveDirectoryIterator. El punto está en la bandera RecursiveIteratorIterator::CHILD_FIRST, el iterador recorrerá primero los archivos y el directorio al final, por lo que una vez que el directorio esté vacío, es seguro usar rmdir().

foreach( new RecursiveIteratorIterator( 
    new RecursiveDirectoryIterator( 'folder', FilesystemIterator::SKIP_DOTS | FilesystemIterator::UNIX_PATHS ), 
    RecursiveIteratorIterator::CHILD_FIRST ) as $value ) {
        $value->isFile() ? unlink( $value ) : rmdir( $value );
}

rmdir( 'folder' );
 4
Author: Danijel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-03-24 20:04:15

Una forma de hacerlo sería:

function unlinker($file)
{
    unlink($file);
}
$files = glob('*.*');
array_walk($files,'unlinker');
rmdir($dir);
 1
Author: Adi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-06-29 18:35:30

Para eliminar todos los archivos puede eliminar el directorio y hacer de nuevo.. con una simple línea de código

<?php 
    $dir = '/home/files/';
    rmdir($dir);
    mkdir($dir);
?>
 0
Author: MD Alauddin Al-Amin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-20 09:40:06