FRIHOSTFORUMSFAQTOSBLOGSDIRECTORY
You are invited to Log in or Register a Frihost Account!

How to find size of directory and remove it?

 


imagefree
How can we find the size of directory and how can we remove it using php?


I want to delete a directory so that all the files inside it are also deleted.(I MEAN I WANT TO DELETE THE WHOLE TREE.)

Thanks
rvec
http://www.ozzu.com/programming-forum/php-delete-directory-folder-t47492.html
Quote:
Code:

function delete_directory($dirname) {
if (is_dir($dirname))
$dir_handle = opendir($dirname);
if (!$dir_handle)
return false;
while($file = readdir($dir_handle)) {
if ($file != "." && $file != "..") {
if (!is_dir($dirname."/".$file))
unlink($dirname."/".$file);
else
delete_directory($dirname.'/'.$file);
}
}
closedir($dir_handle);
rmdir($dirname);
return true;
}



This code can easily be improved upon, as it's a quick hack, but it takes a directory as an argument and then uses functional recursion to delete all files and folders within, and then finally removes the directory. Nice and quick, too.
imagefree
Thanks rvec. Really nice sharing
rvec
oh forgot this link: http://nl2.php.net/filesize

for the filesize Razz
imagefree
yes. but isnt it just for files?
rvec
yes, you have to check every file and add it all together.

edit:
Code:

function filesize_directory($dirname) {
    if (is_dir($dirname))
        $dir_handle = opendir($dirname);
    if (!$dir_handle)
        return false;
    while($file = readdir($dir_handle)) {
        if ($file != "." && $file != "..") {
            if (!is_dir($dirname."/".$file))
                $size += filesize($dirname."/".$file);
        else
            $size += filesize_directory($dirname.'/'.$file);
        }
    }
    closedir($dir_handle);
    return $size;
}


that will return the total size of the dir. So if you'd want to delete all files in 'dir' if the total filesize exceeds 1mb use this code:
Code:

<?php
//the two functions here
if (filesize_directory('dir') > 1024) delete_directory('dir');

Reply to topic    Frihost Forum Index -> Scripting -> Php and MySQL

FRIHOST HOME | FAQ | TOS | ABOUT US | CONTACT US | SITE MAP
© 2005-2007 Frihost, forums powered by phpBB.