[英]A recursive remove directory function for PHP?
I am using PHP to move the contents of a images subfolder我正在使用 PHP 移动图像子文件夹的内容
GalleryName/images/画廊名称/图片/
into another folder.到另一个文件夹。 After the move, I need to delete the GalleryName directory and everything else inside it .移动后,我需要删除 GalleryName 目录和其中的所有其他内容。
I know that rmdir()
won't work unless the directory is empty.我知道除非目录为空,否则rmdir()
将无法工作。 I've spent a while trying to build a recursive function to scandir()
starting from the top and then unlink()
if it's a file and scandir()
if it's a directory, then rmdir()
each empty directory as I go.我花了一段时间尝试从顶部开始构建一个scandir()
递归函数,然后unlink()
如果它是一个文件和scandir()
如果它是一个目录,然后rmdir()
每个空目录我走。
So far it's not working exactly right, and I began to think -- isn't this a ridiculously simple function that PHP should be able to do?到目前为止,它的工作并不完全正确,我开始思考——这难道不是 PHP 应该能够做到的一个非常简单的函数吗? Removing a directory?删除目录?
So is there something I'm missing?那么有什么我想念的吗? Or is there at least a proven function that people use for this action?或者至少有一个经过验证的功能可供人们用于此操作?
Any help would be appreciated.任何帮助,将不胜感激。
PS I trust you all here more than the comments on the php.net site -- there are hundreds of functions there but I am interested to hear if any of you here recommend one over others. PS 我比 php.net 站点上的评论更相信你们所有人——那里有数百个功能,但我很想听听你们中的任何人是否推荐一个而不是其他功能。
What about this?那这个呢?
function rmdir_recursive($dirPath){
if(!empty($dirPath) && is_dir($dirPath) ){
$dirObj= new RecursiveDirectoryIterator($dirPath, RecursiveDirectoryIterator::SKIP_DOTS); //upper dirs not included,otherwise DISASTER HAPPENS :)
$files = new RecursiveIteratorIterator($dirObj, RecursiveIteratorIterator::CHILD_FIRST);
foreach ($files as $path)
$path->isDir() && !$path->isLink() ? rmdir($path->getPathname()) : unlink($path->getPathname());
rmdir($dirPath);
return true;
}
return false;
}
This is the recursive function I've created/modifed and that finally seems to be working.这是我创建/修改的递归函数,它最终似乎起作用了。 Hopefully there isn't anything too dangerous in it.希望里面没有什么太危险的东西。
function destroy_dir($dir) {
if (!is_dir($dir) || is_link($dir)) return unlink($dir);
foreach (scandir($dir) as $file) {
if ($file == '.' || $file == '..') continue;
if (!destroy_dir($dir . DIRECTORY_SEPARATOR . $file)) {
chmod($dir . DIRECTORY_SEPARATOR . $file, 0777);
if (!destroy_dir($dir . DIRECTORY_SEPARATOR . $file)) return false;
};
}
return rmdir($dir);
}
If the server of application runs linux, just use the shell_exec() function, and provide it the rm -R command, like this:如果应用程序的服务器运行的是 linux,只需使用 shell_exec() 函数,并为其提供 rm -R 命令,如下所示:
$realPath = realpath($dir_path);
if($realPath === FALSE){
throw new \Exception('Directory does not exist');
}
shell_exec("rm ". escapeshellarg($realPath) ." -R");
Explanation:解释:
Removes the specified directory recursively only if the path exists and escapes the path so that it can only be used as a shell argument to avoid shell command injection.仅当路径存在时递归删除指定目录并转义路径,使其只能用作 shell 参数以避免 shell 命令注入。
If you wouldnt use escapeshellarg
one could execute commands by naming the directory to be removed after a command.如果您不使用escapeshellarg
则可以通过在命令后命名要删除的目录来执行命令。
I've adapted a function which handles hidden unix files with the dot prefix and uses glob:我改编了一个函数,它处理带有点前缀的隐藏 unix 文件并使用 glob:
public static function deleteDir($path) {
if (!is_dir($path)) {
throw new InvalidArgumentException("$path is not a directory");
}
if (substr($path, strlen($path) - 1, 1) != '/') {
$path .= '/';
}
$dotfiles = glob($path . '.*', GLOB_MARK);
$files = glob($path . '*', GLOB_MARK);
$files = array_merge($files, $dotfiles);
foreach ($files as $file) {
if (basename($file) == '.' || basename($file) == '..') {
continue;
} else if (is_dir($file)) {
self::deleteDir($file);
} else {
unlink($file);
}
}
rmdir($path);
}
There is another thread with more examples here: How do I recursively delete a directory and its entire contents (files + sub dirs) in PHP?这里还有另一个包含更多示例的线程: How do I recursively delete a directory and its entire contents (files + sub dirs) in PHP?
If you are using Yii then you can leave it to the framework:如果你使用 Yii,那么你可以把它留给框架:
CFileHelper::removeDirectory($my_directory);
I prefer an enhaced method derived from the php help pages http://php.net/manual/en/function.rmdir.php#115598我更喜欢从 php 帮助页面http://php.net/manual/en/function.rmdir.php#115598派生的增强方法
// check accidential empty, root or relative pathes
if (!empty($path) && ...)
{
if (PHP_OS === 'Windows')
{
exec('rd /s /q "'.$path.'"');
}
else
{
exec('rm -rf "'.$path.'"');
}
}
else
{
error_log('path not valid:$path'.var_export($path, true));
}
reasons for my decision:我的决定的原因:
public static function rrmdir($dir)
{
if (is_dir($dir)) {
$files = scandir($dir);
foreach ($files as $file) {
if ($file != "." && $file != "..") {
if (filetype($dir . "/" . $file) == "dir")
self::rrmdir($dir . "/" . $file);
else
unlink($dir . "/" . $file);
}
}
reset($files);
rmdir($dir);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.