deleting a folder thats not empty
Moderator: General Moderators
deleting a folder thats not empty
is something like this possible in php? i know i can delete an empty folder but how do i delete one that has contents?
-
kingconnections
- Forum Contributor
- Posts: 137
- Joined: Thu Jul 14, 2005 4:28 pm
You can do this with php 5 (I think 5.1+) and use SPL
The $file->delete() is probably incorrect as this is from memory, you also have to filter out the '.' and '..', but with SPL you can delete an entire directory tree with about 4 or 5 lines of code similar to the above. A good place to start is http://www.wiki.cc/php and http://www.php.net/spl
Code: Select all
foreach( new RecursiveIteratorIterator( new RecursiveDirectoryIterator('my/path/') ) as $file )
{
$file->delete() ;
}- John Cartwright
- Site Admin
- Posts: 11470
- Joined: Tue Dec 23, 2003 2:10 am
- Location: Toronto
- Contact:
which operating system?
with linux you can do this easily with
with linux you can do this easily with
Code: Select all
rm -r /path/to/directory/im gonna see if this snippet will work
Code: Select all
<?php
function remove_directory($dir) {
if ($handle = opendir("$dir")) {
while (false !== ($item = readdir($handle))) {
if ($item != "." && $item != "..") {
if (is_dir("$dir/$item")) {
remove_directory("$dir/$item");
} else {
unlink("$dir/$item");
echo " removing $dir/$item<br>\n";
}
}
}
closedir($handle);
rmdir($dir);
echo "removing $dir<br>\n";
}
}
remove_directory("/path/to/dir");
?>-
impulse()
- Forum Regular
- Posts: 748
- Joined: Wed Aug 09, 2006 8:36 am
- Location: Staffordshire, UK
- Contact:
I'm not sure how you delete files on Windows server but I believe the following code will identify if the directory is empty or not.
NOTE: This works on a Linux system but I'm not sure how many element will be in the $contents array if the directory is empty on a Windows server.
If that doesn't work, try using
while the directory IS empty to see how many elements are in the array and then change accordingly.
Hope that helps,
NOTE: This works on a Linux system but I'm not sure how many element will be in the $contents array if the directory is empty on a Windows server.
Code: Select all
$dirContents = opendir("directoryPath");
$i = 0;
while ($files = readdir($dirContents)) {
$contents[$i] = $files;
$i++;
}
if (count($contents) <= 2) {
// This will run if the directory is empty.
}
else {
// This will run if the there are files in the directory
}Code: Select all
print_r($contents);Code: Select all
if (count($contents) <= 2) {Hope that helps,