Eliminar todos los archivos de una carpeta usando PHP?


Por ejemplo, tenía una carpeta llamada `Temp' y quería eliminar o vaciar todos los archivos de esta carpeta usando PHP. ¿Puedo hacer esto?

Author: Peter Mortensen, 2011-01-04

15 answers

$files = glob('path/to/temp/*'); // get all file names
foreach($files as $file){ // iterate files
  if(is_file($file))
    unlink($file); // delete file
}

Si desea eliminar archivos 'ocultos' como .htaccess, usted tiene que utilizar

$files = glob('path/to/temp/{,.}*', GLOB_BRACE);
 558
Author: Floern,
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-10-04 17:04:13

Si desea eliminar todo de la carpeta (incluidas las subcarpetas), use esta combinación de array_map, unlink y glob:

array_map('unlink', glob("path/to/temp/*"));

Actualización

Esta llamada también puede manejar directorios vacíos-gracias por el consejo, @ mojuba!

array_map('unlink', array_filter((array) glob("path/to/temp/*")));
 224
Author: Stichoza,
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
2018-09-14 10:33:32

Aquí hay un enfoque más moderno usando la Biblioteca PHP Estándar (SPL) .

$dir = "path/to/directory";
$di = new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS);
$ri = new RecursiveIteratorIterator($di, RecursiveIteratorIterator::CHILD_FIRST);
foreach ( $ri as $file ) {
    $file->isDir() ?  rmdir($file) : unlink($file);
}
return true;
 75
Author: Yamiko,
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-12 12:13:23
foreach (new DirectoryIterator('/path/to/directory') as $fileInfo) {
    if(!$fileInfo->isDot()) {
        unlink($fileInfo->getPathname());
    }
}
 67
Author: JakeParis,
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-12 16:29:34

Este código de http://php.net/unlink:

/**
 * Delete a file or recursively delete a directory
 *
 * @param string $str Path to file or directory
 */
function recursiveDelete($str) {
    if (is_file($str)) {
        return @unlink($str);
    }
    elseif (is_dir($str)) {
        $scan = glob(rtrim($str,'/').'/*');
        foreach($scan as $index=>$path) {
            recursiveDelete($path);
        }
        return @rmdir($str);
    }
}
 19
Author: Poelinca Dorin,
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-05-16 21:19:38
$dir = 'your/directory/';
foreach(glob($dir.'*.*') as $v){
    unlink($v);
}
 13
Author: Haim Evgi,
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
2011-01-04 13:45:19

Ver readdiry desvincular.

<?php
    if ($handle = opendir('/path/to/files'))
    {
        echo "Directory handle: $handle\n";
        echo "Files:\n";

        while (false !== ($file = readdir($handle)))
        {
            if( is_file($file) )
            {
                unlink($file);
            }
        }
        closedir($handle);
    }
?>
 10
Author: StampedeXV,
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-05-16 21:18:32

Asumir que tiene una carpeta con MUCHOS archivos que los leen todos y luego los eliminan en dos pasos no es tan satisfactorio. Creo que la forma más eficaz de eliminar archivos es simplemente usar un comando del sistema.

Por ejemplo en linux uso:

exec('rm -f '. $absolutePathToFolder .'*');

O esto si desea una eliminación recursiva sin la necesidad de escribir una función recursiva

exec('rm -f -r '. $absolutePathToFolder .'*');

Los mismos comandos exactos existen para cualquier sistema operativo soportado por PHP. Tenga en cuenta que esta es una forma de eliminar archivos. $absolutePathToFolder SE debe comprobar y asegurar antes de ejecutar este código y se deben conceder permisos.

 8
Author: Dario Corno,
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-09-28 13:39:37

La mejor y más sencilla manera de eliminar todos los archivos de una carpeta en PHP

$files = glob('my_folder/*'); //get all file names
foreach($files as $file){
    if(is_file($file))
    unlink($file); //delete file
}

Obtuve este código fuente de aquí - http://www.codexworld.com/delete-all-files-from-folder-using-php /

 7
Author: JoyGuru,
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-06-21 06:51:20

Otra solución: Esta clase elimina todos los archivos, subdirectorios y archivos en los subdirectorios.

class Your_Class_Name {
    /**
     * @see http://php.net/manual/de/function.array-map.php
     * @see http://www.php.net/manual/en/function.rmdir.php 
     * @see http://www.php.net/manual/en/function.glob.php
     * @see http://php.net/manual/de/function.unlink.php
     * @param string $path
     */
    public function delete($path) {
        if (is_dir($path)) {
            array_map(function($value) {
                $this->delete($value);
                rmdir($value);
            },glob($path . '/*', GLOB_ONLYDIR));
            array_map('unlink', glob($path."/*"));
        }
    }
}
 4
Author: tommy,
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-07-17 13:44:54

La función Unlinkr elimina recursivamente todas las carpetas y archivos en la ruta dada asegurándose de que no elimine el script en sí.

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('..', '.')))  {
            echo "<p>opening directory $file </p>";
            unlinkr($file, $pattern);
            //remove the directory itself
            echo "<p> deleting directory $file </p>";
            rmdir($file);
        } else if(is_file($file) and ($file != __FILE__)) {
            // make sure you don't delete the current script
            echo "<p>deleting file $file </p>";
            unlink($file); 
        }
    }
}

Si desea eliminar todos los archivos y carpetas donde coloca este script, llámelo de la siguiente manera

//get current working directory
$dir = getcwd();
unlinkr($dir);

Si desea eliminar solo los archivos php, llámelo de la siguiente manera

unlinkr($dir, "*.php");

También puede usar cualquier otra ruta para eliminar los archivos

unlinkr("/home/user/temp");

Esto eliminará todos los archivos en el directorio home/user/temp.

 4
Author: Tofeeq,
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-11-20 07:28:03

Publicó una clase de manejo de archivos y carpetas de propósito general para copiar, mover, eliminar, calcular el tamaño, etc., que puede manejar un solo archivo o un conjunto de carpetas.

Https://gist.github.com/4689551

Para usar:

Para copiar (o mover) un solo archivo o un conjunto de carpetas/archivos:

$files = new Files();
$results = $files->copyOrMove('source/folder/optional-file', 'target/path', 'target-file-name-for-single-file.only', 'copy');

Eliminar un solo archivo o todos los archivos y carpetas en una ruta:

$files = new Files();
$results = $files->delete('source/folder/optional-file.name');

Calcular el tamaño de un solo archivo o un conjunto de archivos en un conjunto de carpetas:

$files = new Files();
$results = $files->calculateSize('source/folder/optional-file.name');
 3
Author: AmyStephen,
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-02-01 06:05:41

Para mí, la solución con readdir fue mejor y funcionó como un encanto. Con glob, la función estaba fallando con algunos escenarios.

// Remove a directory recursively
function removeDirectory($dirPath) {
    if (! is_dir($dirPath)) {
        return false;
    }

    if (substr($dirPath, strlen($dirPath) - 1, 1) != '/') {
        $dirPath .= '/';
    }

    if ($handle = opendir($dirPath)) {

        while (false !== ($sub = readdir($handle))) {
            if ($sub != "." && $sub != ".." && $sub != "Thumb.db") {
                $file = $dirPath . $sub;

                if (is_dir($file)) {
                    removeDirectory($file);
                } else {
                    unlink($file);
                }
            }
        }

        closedir($handle);
    }

    rmdir($dirPath);
}
 1
Author: Tiago Silva Pereira,
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
2018-03-13 04:44:24

He actualizado la respuesta de @Stichoza para eliminar archivos a través de subcarpetas.

function glob_recursive($pattern, $flags = 0) {
    $fileList = glob($pattern, $flags);
    foreach (glob(dirname($pattern).'/*', GLOB_ONLYDIR|GLOB_NOSORT) as $dir) {
        $subPattern = $dir.'/'.basename($pattern);
        $subFileList = glob_recursive($subPattern, $flags);
        $fileList = array_merge($fileList, $subFileList);
    }
    return $fileList;
}

function glob_recursive_unlink($pattern, $flags = 0) {
    array_map('unlink', glob_recursive($pattern, $flags));
}
 0
Author: tzi,
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-10-17 12:57:08
 <?
//delete all files from folder  & sub folders
function listFolderFiles($dir)
{
    $ffs = scandir($dir);
    echo '<ol>';
    foreach ($ffs as $ff) {
        if ($ff != '.' && $ff != '..') {
            if (file_exists("$dir/$ff")) {
                unlink("$dir/$ff");
            }
            echo '<li>' . $ff;
            if (is_dir($dir . '/' . $ff)) {
                listFolderFiles($dir . '/' . $ff);
            }
            echo '</li>';
        }
    }
    echo '</ol>';
}
$arr = array(
    "folder1",
    "folder2"
);
for ($x = 0; $x < count($arr); $x++) {
    $mm = $arr[$x];
    listFolderFiles($mm);
}
//end
?> 
 0
Author: user5579724,
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-11-19 05:51:51