note 98499 modified in function.rmdir by danbrown

From: Date: Fri, 18 Jun 2010 22:34:22 +0000
Subject: note 98499 modified in function.rmdir by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-170254@lists.php.net to get a copy of this message
This isn't my code, but just thought I would share, since it took me so long to find. This is a function to delete a folder, all sub-folders, and files in one clean move. Just tell it what directory you want deleted, in relation to the page that this function is executed. Then set $empty = true if you want the folder just emptied, but not deleted. If you set $empty = false, or just simply leave it out, the given directory will be deleted, as well. <?php function deleteAll($directory, $empty = false) { if(substr($directory,-1) == "/") { $directory = substr($directory,0,-1); } if(!file_exists($directory) || !is_dir($directory)) { return false; } elseif(!is_readable($directory)) { return false; } else { $directoryHandle = opendir($directory); while ($contents = readdir($directoryHandle)) { if($contents != '.' && $contents != '..') { $path = $directory . "/" . $contents; if(is_dir($path)) { deleteAll($path); } else { unlink($path); } } } closedir($directoryHandle); if($empty == false) { if(!rmdir($directory)) { return false; } } return true; } } ?> --was-- This isn't my code, but just thought I would share, since it took me so long to find. This is a function to delete a folder, all sub-folders, and files in one clean move. Just tell it what directory you want deleted, in relation to the page that this function is executed. Then set $empty = true if you want the folder just emptied, but not deleted. If you set $empty = false, or just simply leave it out, the given directory will be deleted, as well. function deleteAll($directory, $empty = false) { if(substr($directory,-1) == "/") { $directory = substr($directory,0,-1); } if(!file_exists($directory) || !is_dir($directory)) { return false; } elseif(!is_readable($directory)) { return false; } else { $directoryHandle = opendir($directory); while ($contents = readdir($directoryHandle)) { if($contents != '.' && $contents != '..') { $path = $directory . "/" . $contents; if(is_dir($path)) { deleteAll($path); } else { unlink($path); } } } closedir($directoryHandle); if($empty == false) { if(!rmdir($directory)) { return false; } } return true; } } http://php.net/manual/en/function.rmdir.php

« previous php.notes (#170254) next »