Usuwanie wszystkich plików z folderu za pomocą PHP?

Na przykład miałem folder o nazwie `Temp ' i chciałem usunąć lub usunąć wszystkie pliki z tego folderu za pomocą PHP. Mogę to zrobić?

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
}

Jeśli chcesz usunąć 'ukryte' pliki jak .htaccess, musisz użyć

$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/doraprojects.net/template/agent.layouts/content.php on line 54
2016-10-04 17:04:13

Jeśli chcesz usunąć wszystko z folderu (w tym podfoldery), użyj tej kombinacji array_map, unlink i glob:

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

Update

To wywołanie może również obsługiwać puste katalogi-dzięki za wskazówkę, @ 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/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-14 10:33:32

Oto bardziej nowoczesne podejście przy użyciu standardowej biblioteki PHP (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/doraprojects.net/template/agent.layouts/content.php on line 54
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/doraprojects.net/template/agent.layouts/content.php on line 54
2016-04-12 16:29:34

Ten kod z 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/doraprojects.net/template/agent.layouts/content.php on line 54
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/doraprojects.net/template/agent.layouts/content.php on line 54
2011-01-04 13:45:19

Zobacz readdir i unlink .

<?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/doraprojects.net/template/agent.layouts/content.php on line 54
2015-05-16 21:18:32

Założenie, że masz folder z wieloma plikami, które odczytują je wszystkie, a następnie usuwają je w dwóch krokach, nie jest takie skuteczne. Uważam, że najbardziej skutecznym sposobem usuwania plików jest użycie polecenia systemowego.

Na przykład na Linuksie używam:

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

Lub to, jeśli chcesz usunąć rekurencyjnie bez potrzeby pisania funkcji rekurencyjnej

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

Te same polecenia istnieją dla każdego systemu operacyjnego obsługiwanego przez PHP. Należy pamiętać, że jest to skuteczny sposób usuwania plików. przed uruchomieniem tego kodu należy sprawdzić i zabezpieczyć $absolutePathToFolder oraz przyznać uprawnienia.

 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/doraprojects.net/template/agent.layouts/content.php on line 54
2017-09-28 13:39:37

Prosty i najlepszy sposób na usunięcie wszystkich plików z folderu w PHP

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

Mam ten kod źródłowy stąd - 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/doraprojects.net/template/agent.layouts/content.php on line 54
2016-06-21 06:51:20

Inne rozwiązanie: Ta klasa usuwa wszystkie pliki, podkatalogi i pliki w podkatalogach.

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/doraprojects.net/template/agent.layouts/content.php on line 54
2014-07-17 13:44:54

Funkcja Unlinkr usuwa rekurencyjnie wszystkie foldery i pliki w podanej ścieżce, upewniając się, że nie usunie samego skryptu.

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); 
        }
    }
}

Jeśli chcesz usunąć wszystkie pliki i foldery, w których umieścisz ten skrypt, wywołaj go w następujący sposób

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

Jeśli chcesz po prostu usunąć tylko pliki php, wywołaj to w następujący sposób

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

Możesz również użyć dowolnej innej ścieżki do usunięcia plików

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

Spowoduje to usunięcie wszystkich plików w katalogu 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/doraprojects.net/template/agent.layouts/content.php on line 54
2015-11-20 07:28:03

Opublikował klasę obsługi plików i folderów ogólnego przeznaczenia do kopiowania, przenoszenia, usuwania, obliczania rozmiaru itp., który może obsługiwać pojedynczy plik lub zestaw folderów.

Https://gist.github.com/4689551

Do użycia:

Aby skopiować (lub przenieść) pojedynczy plik lub zestaw folderów/plików:

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

Usuń pojedynczy plik lub wszystkie pliki i foldery w ścieżce:

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

Oblicz rozmiar pojedynczego pliku lub zestawu plików w zestawie folderów:

$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/doraprojects.net/template/agent.layouts/content.php on line 54
2013-02-01 06:05:41

Dla mnie rozwiązanie z readdir było najlepsze i działało jak urok. Z glob, funkcja zawodziła w niektórych scenariuszach.

// 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/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-13 04:44:24

Zaktualizowałem odpowiedź @Stichoza, aby usunąć Pliki za pomocą podfolderów.

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/doraprojects.net/template/agent.layouts/content.php on line 54
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/doraprojects.net/template/agent.layouts/content.php on line 54
2015-11-19 05:51:51