2012-06-29 37 views
28

Tôi có cách tôi có thể sử dụng tìm kiếm RegExp hoặc Wildcard để xóa nhanh tất cả các tệp trong thư mục rồi xóa thư mục đó bằng PHP, KHÔNG sử dụng "exec " chỉ huy? Máy chủ của tôi không cho phép tôi sử dụng lệnh đó. Một vòng lặp đơn giản của một số loại sẽ đủ.PHP: Hủy liên kết tất cả các tệp trong thư mục, và sau đó xóa thư mục đó

tôi cần cái gì đó sẽ thực hiện logic đằng sau những tuyên bố sau, nhưng rõ ràng, sẽ là hợp lệ:

 

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

http://stackoverflow.com/questions/3349753/php-delete- directory-with-files-in-it – John

+0

http://stackoverflow.com/questions/3338123/how-do-i-recursively-delete-a-directory-and-its-entire-contents-filessub-dirs – Jocelyn

Trả lời

75

Sử dụng glob để tìm tất cả các file phù hợp với một mô hình.

function recursiveRemoveDirectory($directory) 
{ 
    foreach(glob("{$directory}/*") as $file) 
    { 
     if(is_dir($file)) { 
      recursiveRemoveDirectory($file); 
     } else { 
      unlink($file); 
     } 
    } 
    rmdir($directory); 
} 
+2

Tôi nhận một lỗi 'mức tối đa chức năng làm tổ của '100' đạt được ' – Smith

+0

Tôi đã gặp sự cố về quyền với chức năng' scandir' trong mã của tôi, giờ nó hoạt động hoàn hảo với phiên bản này! – SeinopSys

+1

glob sẽ xử lý các tệp ẩn? – amar

16

Sử dụng glob() để dễ dàng duyệt qua thư mục để xóa tệp, sau đó bạn có thể xóa thư mục.

foreach (glob($dir."/*.*") as $filename) { 
    if (is_file($filename)) { 
     unlink($filename); 
    } 
} 
rmdir($dir); 
+12

mã này là nguy hiểm, đường dẫn nên được bao gồm trong glob như vậy 'glob ($ dir." /*.* ")'.tôi đã thử nó và nó xóa sạch tất cả các thư mục bao gồm những cái đầu của công việc khó khăn của tôi – Smith

1

Một cách để làm việc đó sẽ là:

function unlinker($file) 
{ 
    unlink($file); 
} 
$files = glob('*.*'); 
array_walk($files,'unlinker'); 
rmdir($dir); 
9

Chức năng glob() làm những gì bạn đang tìm kiếm. Nếu bạn đang ở trên PHP 5.3+ bạn có thể làm một cái gì đó như thế này:

$dir = ... 
array_walk(glob($dir . '/*'), function ($fn) { 
    if (is_file($fn)) 
     unlink($fn); 
}); 
unlink($dir); 
2

Bạn có thể sử dụng Symfony Filesystem component, để tránh tái phát minh ra bánh xe, vì vậy bạn có thể làm

use Symfony\Component\Filesystem\Filesystem; 

$filesystem = new Filesystem(); 

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

Nếu bạn thích để quản lý mã chính mình, đây là codebase Symfony cho các phương pháp có liên quan

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

Hãy thử cách dễ dàng:

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

Trong Function cho remove 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"); 
+2

Trong khi đoạn mã này có thể giải quyết câu hỏi, [bao gồm cả một lời giải thích] (http://meta.stackexchange.com/questions/114762/explaining-entirely- các giải pháp dựa trên mã) thực sự giúp cải thiện chất lượng bài đăng của bạn. Hãy nhớ rằng bạn đang trả lời câu hỏi cho người đọc trong tương lai và những người đó có thể không biết lý do cho đề xuất mã của bạn. – Bono

4

Một cách đơn giản và hiệu quả để xóa tất cả các file và thư mục đệ quy với Standard PHP Library, phải cụ thể, RecursiveIteratorIteratorRecursiveDirectoryIterator. Vấn đề là trong cờ RecursiveIteratorIterator::CHILD_FIRST, trình lặp sẽ lặp qua các tệp trước và thư mục ở cuối, vì vậy khi thư mục trống, an toàn để sử dụng 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'); 
0

để loại bỏ tất cả các file bạn có thể loại bỏ các thư mục và thực hiện một lần nữa .. với một dòng mã đơn giản

<?php 
    $dir = '/home/files/'; 
    rmdir($dir); 
    mkdir($dir); 
?> 
Các vấn đề liên quan