PHP delete the contents of a directory

六月ゝ 毕业季﹏ 提交于 2019-12-06 22:39:58

问题


How do I do that? Is there any method provided by kohana 3?


回答1:


To delete a directory and all this content, you'll have to write some recursive deletion function -- or use one that already exists.

You can find some examples in the user's notes on the documentation page of rmdir ; for instance, here's the one proposed by bcairns in august 2009 (quoting) :

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



回答2:


I suggest this way, simple and direct.

    $files = glob('your/folder/' . '*', GLOB_MARK);
    foreach($files as $file)
    {
        if (is_dir($file)) {
            self::deleteDir($file);
        } else {
            unlink($file);
        }
    }



回答3:


have you tried unlink in the directory ?

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

This deletes filenames starting from N




回答4:


I'm not sure about Kohana 3, but I'd use a DirectoryIterator() and unlink() in conjunction.




回答5:


The solution of Pascal does not work on all OS. Therefor I have created another solution. The code is part of a static class library and is static.
It deletes all files and directories in a given parent directory.
The function is recursive for the subdirectories and has an option not to delete the parent directory ($keepFirst).
If the parent directory does not exist or is not a directory 'null' is returned. In case of a successful deletion 'true' is returned.

/**
* 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


来源:https://stackoverflow.com/questions/2205187/php-delete-the-contents-of-a-directory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!