From 4d47e8e3bcbb31435593de9d567723e5d87641bd Mon Sep 17 00:00:00 2001 From: Andreas Gohr Date: Mon, 6 Jan 2014 20:20:15 +0100 Subject: added recursive delete function to io.php --- inc/io.php | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) (limited to 'inc/io.php') diff --git a/inc/io.php b/inc/io.php index eff0279ac..30f34ad3c 100644 --- a/inc/io.php +++ b/inc/io.php @@ -400,6 +400,55 @@ function io_mkdir_p($target){ return 0; } +/** + * Recursively delete a directory + * + * @author Andreas Gohr + * @param string $path + * @param bool $removefiles defaults to false which will delete empty directories only + * @return bool + */ +function io_rmdir($path, $removefiles = false) { + if(!is_string($path) || $path == "") return false; + + if(is_dir($path) && !is_link($path)) { + $dirs = array(); + $files = array(); + + if(!$dh = @opendir($path)) return false; + while($f = readdir($dh)) { + if($f == '..' || $f == '.') continue; + + // collect dirs and files first + if(is_dir("$path/$f") && !is_link("$path/$f")) { + $dirs[] = "$path/$f"; + } else if($removefiles) { + $files[] = "$path/$f"; + } else { + return false; // abort when non empty + } + + } + closedir($dh); + + // now traverse into directories first + foreach($dirs as $dir) { + if(!io_rmdir($dir, $removefiles)) return false; // abort on any error + } + + // now delete files + foreach($files as $file) { + if(!@unlink($file)) return false; //abort on any error + } + + // remove self + return @rmdir($path); + } else if($removefiles) { + return @unlink($path); + } + return false; +} + /** * Creates a directory using FTP * -- cgit v1.2.3 From d8cf4dd43ecd37c371acf9bc6c17998b65d42ba4 Mon Sep 17 00:00:00 2001 From: Andreas Gohr Date: Mon, 6 Jan 2014 21:15:50 +0100 Subject: treat non-existing files as success on delete --- inc/io.php | 1 + 1 file changed, 1 insertion(+) (limited to 'inc/io.php') diff --git a/inc/io.php b/inc/io.php index 30f34ad3c..892f93759 100644 --- a/inc/io.php +++ b/inc/io.php @@ -410,6 +410,7 @@ function io_mkdir_p($target){ */ function io_rmdir($path, $removefiles = false) { if(!is_string($path) || $path == "") return false; + if(!file_exists($path)) return true; // it's already gone or was never there, count as success if(is_dir($path) && !is_link($path)) { $dirs = array(); -- cgit v1.2.3 From 8426a3ee6fca3bd0fc582d6c405f5d30e12028d0 Mon Sep 17 00:00:00 2001 From: Andreas Gohr Date: Sun, 19 Jan 2014 20:10:49 +0100 Subject: check for false in readdir --- inc/io.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'inc/io.php') diff --git a/inc/io.php b/inc/io.php index 892f93759..c5225a2e0 100644 --- a/inc/io.php +++ b/inc/io.php @@ -417,7 +417,7 @@ function io_rmdir($path, $removefiles = false) { $files = array(); if(!$dh = @opendir($path)) return false; - while($f = readdir($dh)) { + while(false !== ($f = readdir($dh))) { if($f == '..' || $f == '.') continue; // collect dirs and files first -- cgit v1.2.3