PHP删除目录内容

8

我该怎么做?Kohana 3提供了任何方法吗?


1
这是一个PHP框架,尽管这个问题与它没有任何关系,但已经重新标记了。 - The Pixel Developer
5个回答

10
为了删除一个目录及其所有内容,您需要编写一些递归删除函数——或使用已经存在的函数。
您可以在rmdir文档页面的用户笔记中找到一些示例;例如,这里是bcairns在2009年8月提出的一个示例 (引用)
<?php
// ensure $dir ends with a slash
function delTree($dir) {
    $files = glob( $dir . '*', GLOB_MARK );
    foreach( $files as $file ){
        if( substr( $file, -1 ) == '/' )
            delTree( $file );
        else
            unlink( $file );
    }
    rmdir( $dir );
}
?> 

$files = glob( $dir . '*', GLOB_MARK ); -> 请解释这行代码。谢谢。 - ed.
glob 函数(参见 http://php.net/glob)将返回与模式匹配的所有文件 -- * 将匹配所有文件,这意味着 glob 将返回 $dir 指向的目录中的所有文件列表;;GLOB_MARK 表示“在返回的每个目录后添加一个斜杠”。 - Pascal MARTIN
2
如果您只想删除文件夹中的内容而不是文件夹本身,请删除 rmdir($dir); 行。 - PaulSkinner
此外,您可以添加 GLOB_NOSORT 以加快删除速度,因此它将是 $files = glob( $dir . '*', GLOB_MARK | GLOB_NOSORT ); - terales

5
我建议采用这种方式,简单直接。
    $files = glob('your/folder/' . '*', GLOB_MARK);
    foreach($files as $file)
    {
        if (is_dir($file)) {
            self::deleteDir($file);
        } else {
            unlink($file);
        }
    }

0
Pascal的解决方案并不适用于所有操作系统。因此,我创建了另一个解决方案。该代码是静态类库的一部分,并且是静态的。
它可以删除给定父目录中的所有文件和目录。
对于子目录,该函数是递归的,并具有不删除父目录($keepFirst)的选项。
如果父目录不存在或不是目录,则返回“null”。在成功删除的情况下,返回“true”。
/**
* Deletes all files in the given directory, also the subdirectories.
* @param string  $dir       Name of the directory
* @param boolean $keepFirst [Optional] indicator for first directory.
* @return null | true
*/
public static function deltree( $dir, $keepFirst = false ) {
  // First check if it is a directory.
  if (! is_dir( $dir ) ) {
     return null;
  }

  if ($handle = opendir( $dir ) ) {
     while (false !== ( $fileName = readdir($handle) ) ) {
        // Skips the hidden directory files.
        if ($fileName == "." || $fileName == "..") {
           continue;
        }

        $dpFile = sprintf( "%s/%s", $dir, $fileName );

        if (is_dir( $dpFile ) ) {
           self::deltree( $dpFile );
        } else {
           unlink( $dpFile );
        }
     }  // while

     // Directory removal, optional not the parent directory.
     if (! $keepFirst ) {
        rmdir( $dir );
     }
  }  // if
  return true;
}  // deltree

Pascal的解决方案没有覆盖哪些操作系统? - terales
谢谢,我错过了那个。 - terales

0

你尝试过在目录中使用unlink吗?

      chdir("file");
   foreach (glob("N*") as $filename )
      {
        unlink($filename);
      }

这将删除以N开头的文件名


0

我不确定Kohana 3,但我会同时使用DirectoryIterator()unlink()


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接