我如何在PHP中recursion删除目录及其全部内容(文件+子目录)?
如何在PHP中删除目录及其全部内容(文件和子目录)?
您是否尝试了rmdir
手册页中的第一个注释?
function rrmdir($dir) { if (is_dir($dir)) { $objects = scandir($dir); foreach ($objects as $object) { if ($object != "." && $object != "..") { if (is_dir($dir."/".$object)) rrmdir($dir."/".$object); else unlink($dir."/".$object); } } rmdir($dir); } }
基于Pixel Developer的评论 ,使用SPL的代码片段可能如下所示:
$files = new RecursiveIteratorIterator( new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST ); foreach ($files as $fileinfo) { $todo = ($fileinfo->isDir() ? 'rmdir' : 'unlink'); $todo($fileinfo->getRealPath()); } rmdir($dir);
注意:它没有进行完整性检查,并且使用PHP 5.3.0中的FilesystemIterator引入的SKIP_DOTS标志。 当然, $todo
可能是一个if
/ else
。 重要的一点是, CHILD_FIRST
用于在其父(文件夹)之前首先迭代子文件(文件)。
对于* nix,您可以使用rm -R
的shell_exec
或Windows的DEL /S folder_name
。
删除path中的所有文件和文件夹。
function recurseRmdir($dir) { $files = array_diff(scandir($dir), array('.','..')); foreach ($files as $file) { (is_dir("$dir/$file")) ? recurseRmdir("$dir/$file") : unlink("$dir/$file"); } return rmdir($dir); }
<?php use RecursiveDirectoryIterator; use RecursiveIteratorIterator; use SplFileInfo; # http://stackoverflow.com/a/3352564/283851 # https://gist.github.com/XzaR90/48c6b615be12fa765898 # Forked from https://gist.github.com/mindplay-dk/a4aad91f5a4f1283a5e2 /** * Recursively delete a directory and all of it's contents - egthe equivalent of `rm -r` on the command-line. * Consistent with `rmdir()` and `unlink()`, an E_WARNING level error will be generated on failure. * * @param string $source absolute path to directory or file to delete. * @param bool $removeOnlyChildren set to true will only remove content inside directory. * * @return bool true on success; false on failure */ function rrmdir($source, $removeOnlyChildren = false) { if(empty($source) || file_exists($source) === false) { return false; } if(is_file($source) || is_link($source)) { return unlink($source); } $files = new RecursiveIteratorIterator ( new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST ); //$fileinfo as SplFileInfo foreach($files as $fileinfo) { if($fileinfo->isDir()) { if(rrmdir($fileinfo->getRealPath()) === false) { return false; } } else { if(unlink($fileinfo->getRealPath()) === false) { return false; } } } if($removeOnlyChildren === false) { return rmdir($source); } return true; }
还有另一个线程更多的例子在这里: PHP的recursion删除目录函数?
如果你使用Yii,那么你可以把它留给框架:
CFileHelper::removeDirectory($my_directory);
像这样的东西?
function delete_folder($folder) { $glob = glob($folder); foreach ($glob as $g) { if (!is_dir($g)) { unlink($g); } else { delete_folder("$g/*"); rmdir($g); } } }
增强了@Artefacto的解决scheme – 纠正了错别字和简化代码,适用于空&&非空目录。
function recursive_rmdir($dir) { if( is_dir($dir) ) { $objects = array_diff( scandir($dir), array('..', '.') ); foreach ($objects as $object) { $objectPath = $dir."/".$object; if( is_dir($objectPath) ) recursive_rmdir($objectPath); else unlink($objectPath); } rmdir($dir); } }
unlinkr函数recursion地删除给定path中的所有文件夹和文件,确保它不会删除脚本本身。
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); } } }
如果要删除放置此脚本的所有文件和文件夹,请按以下方式调用它
//get current working directory $dir = getcwd(); unlinkr($dir);
如果你想删除只是PHP文件,然后调用它如下
unlinkr($dir, "*.php");
您也可以使用其他path来删除文件
unlinkr("/home/user/temp");
这将删除home / user / temp目录中的所有文件。
一旦完成运行testing,只需从#unlink和#rmdir类中删除# 。
<?php class RMRFiles { function __construct(){ } public function recScan( $mainDir, $allData = array() ) { // hide files $hidefiles = array( ".", "..") ; //start reading directory $dirContent = scandir( $mainDir ) ; //cycle through foreach ( $dirContent as $key => $content ) { $path = $mainDir . '/' . $content ; // if is readable / file if ( ! in_array( $content, $hidefiles ) ) { if ( is_file( $path ) && is_readable( $path ) ) { #delete files within directory #unlink($path); $allData['unlink'][] = $path ; } // if is readable / directory else if ( is_dir( $path ) && is_readable( $path ) ) { /*recursive*/ $allData = $this->recScan( $path, $allData ) ; #finally remove directory $allData['rmdir'][]=$path; #rmdir($path); } } } return $allData ; } } header("Content-Type: text/plain"); /* Get absolute path of the running script Ex : /home/user/public_html/ */ define('ABPATH', dirname(__file__) . '/'); /* The folder where we store cache files Ex: /home/user/public_html/var/cache */ define('STOREDIR','var/cache'); $rmrf = new RMRFiles(); #here we delete folder content files & directories print_r($rmrf->recScan(ABPATH.STOREDIR)); #finally delete scanned directory ? #rmdir(ABPATH.STOREDIR); ?>
“简单”的代码可以在十岁时读取:
function deleteNonEmptyDir($dir) { if (is_dir($dir)) { $objects = scandir($dir); foreach ($objects as $object) { if ($object != "." && $object != "..") { if (filetype($dir . "/" . $object) == "dir") { deleteNonEmptyDir($dir . "/" . $object); } else { unlink($dir . "/" . $object); } } } reset($objects); rmdir($dir); } }
请注意,我所做的只是扩展/简化和修复(不适用于非空目录)解决scheme在这里: 在PHP中,我怎么recursion删除所有不是空的文件夹?
我从一些StackOverflow讨论中弄明白了这个代码。 我还没有在Linux环境下testing。 它是为了删除一个文件或一个目录,完全是:
function splRm(SplFileInfo $i) { $path = $i->getRealPath(); if ($i->isDir()) { echo 'D - ' . $path . '<br />'; rmdir($path); } elseif($i->isFile()) { echo 'F - ' . $path . '<br />'; unlink($path); } } function splRrm(SplFileInfo $j) { $path = $j->getRealPath(); if ($j->isDir()) { $rdi = new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS); $rii = new RecursiveIteratorIterator($rdi, RecursiveIteratorIterator::CHILD_FIRST); foreach ($rii as $i) { splRm($i); } } splRm($j); } splRrm(new SplFileInfo(__DIR__.'/../dirOrFileName'));
function rmdir_recursive( $dirname ) { /** * FilesystemIterator and SKIP_DOTS */ if ( class_exists( 'FilesystemIterator' ) && defined( 'FilesystemIterator::SKIP_DOTS' ) ) { if ( !is_dir( $dirname ) ) { return false; } foreach( new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $dirname, FilesystemIterator::SKIP_DOTS ), RecursiveIteratorIterator::CHILD_FIRST ) as $path ) { $path->isDir() ? rmdir( $path->getPathname() ) : unlink( $path->getRealPath() ); } return rmdir( $dirname ); } /** * RecursiveDirectoryIterator and SKIP_DOTS */ if ( class_exists( 'RecursiveDirectoryIterator' ) && defined( 'RecursiveDirectoryIterator::SKIP_DOTS' ) ) { if ( !is_dir( $dirname ) ) { return false; } foreach( new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $dirname, RecursiveDirectoryIterator::SKIP_DOTS ), RecursiveIteratorIterator::CHILD_FIRST ) as $path ) { $path->isDir() ? rmdir( $path->getPathname() ) : unlink( $path->getRealPath() ); } return rmdir( $dirname ); } /** * RecursiveIteratorIterator and RecursiveDirectoryIterator */ if ( class_exists( 'RecursiveIteratorIterator' ) && class_exists( 'RecursiveDirectoryIterator' ) ) { if ( !is_dir( $dirname ) ) { return false; } foreach( new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $dirname ), RecursiveIteratorIterator::CHILD_FIRST ) as $path ) { if ( in_array( $path->getFilename(), array( '.', '..' ) ) ) { continue; } $path->isDir() ? rmdir( $path->getPathname() ) : unlink( $path->getRealPath() ); } return rmdir( $dirname ); } /** * Scandir Recursive */ if ( !is_dir( $dirname ) ) { return false; } $objects = scandir( $dirname ); foreach ( $objects as $object ) { if ( $object === '.' || $object === '..' ) { continue; } filetype( $dirname . DIRECTORY_SEPARATOR . $object ) === 'dir' ? rmdir_recursive( $dirname . DIRECTORY_SEPARATOR . $object ) : unlink( $dirname . DIRECTORY_SEPARATOR . $object ); } reset( $objects ); rmdir( $dirname ); return !is_dir( $dirname ); }
glob()函数的例子。 它将recursion删除所有文件和文件夹,包括以点开头的文件。
delete_all( 'folder' ); function delete_all( $item ) { if ( is_dir( $item ) ) { array_map( 'delete_all', array_diff( glob( "$item/{,.}*", GLOB_BRACE ), array( "$item/.", "$item/.." ) ) ); rmdir( $item ); } else { unlink( $item ); } };
@XzaR解决scheme的修改变体。 它删除空文件夹,当所有的文件被删除,它会抛出exception,而不是错误返回false。
function recursivelyRemoveDirectory($source, $removeOnlyChildren = true) { if (empty($source) || file_exists($source) === false) { throw new Exception("File does not exist: '$source'"); } if (is_file($source) || is_link($source)) { if (false === unlink($source)) { throw new Exception("Cannot delete file '$source'"); } } $files = new RecursiveIteratorIterator( new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST ); foreach ($files as $fileInfo) { /** @var SplFileInfo $fileInfo */ if ($fileInfo->isDir()) { if ($this->recursivelyRemoveDirectory($fileInfo->getRealPath()) === false) { throw new Exception("Failed to remove directory '{$fileInfo->getRealPath()}'"); } if (false === rmdir($fileInfo->getRealPath())) { throw new Exception("Failed to remove empty directory '{$fileInfo->getRealPath()}'"); } } else { if (unlink($fileInfo->getRealPath()) === false) { throw new Exception("Failed to remove file '{$fileInfo->getRealPath()}'"); } } } if ($removeOnlyChildren === false) { if (false === rmdir($source)) { throw new Exception("Cannot remove directory '$source'"); } } }
function deltree_cat($folder) { if (is_dir($folder)) { $handle = opendir($folder); while ($subfile = readdir($handle)) { if ($subfile == '.' or $subfile == '..') continue; if (is_file($subfile)) unlink("{$folder}/{$subfile}"); else deltree_cat("{$folder}/{$subfile}"); } closedir($handle); rmdir ($folder); } else { unlink($folder); } }
我使用这个代码…
function rmDirectory($dir) { foreach(glob($dir . '/*') as $file) { if(is_dir($file)) rrmdir($file); else unlink($file); } rmdir($dir); }
或这个…
<?php public static function delTree($dir) { $files = array_diff(scandir($dir), array('.','..')); foreach ($files as $file) { (is_dir("$dir/$file")) ? delTree("$dir/$file") : unlink("$dir/$file"); } return rmdir($dir); } ?>