How To: Delete All Files In A Directory With PHP
- Friday, March 13th, 2009 at 1:08 am
- Comments (0)
I had a nagging issue that started a few weeks ago when I get a lot of email with large attachments (see my last post about emails from my aunt); when I deleted emails from my device the messages are not deleted from the server as they were with my Windows Mobile device. BlackBerry devices do not allow you to setup the mail account yourself (not to any degree of specificity anyways..), so each time I add the account, it is setup as IMAP. The issue is that when I delete items from my device, they are sent to the .Trash folder, and never deleted from the server. This becomes an issue with a small mailbox quota (mine are set to 25mb because I use POP3 on my laptop and delete the messages from the server after they’re downloaded by Thunderbird) which causes the server to reject mail when the mailbox is full.
Surely there is a simple solution, which is to raise the mailbox quota. However, all that does is allow more and more mail to pile up, which would still require me to go in and clear out the trash folder every few weeks (or days, depending on the size of the emails I receive..). So I did some searching and found a nice little snippet of PHP to tackle this issue:
<?
define('PATH', '/home/user/mail/domain.com/mailaccount/.Trash/cur/');
function destroy($dir) {
$mydir = opendir($dir);
while(false !== ($file = readdir($mydir))) {
if($file != "." && $file != "..") {
chmod($dir.$file, 0777);
if(is_dir($dir.$file)) {
chdir('.');
destroy($dir.$file.'/');
rmdir($dir.$file) or DIE("couldn't delete $dir$file<br />");
}
else
unlink($dir.$file) or DIE("couldn't delete $dir$file<br />");
}
}
closedir($mydir);
}
destroy(PATH);
echo 'all done.';
?>
I placed this into a PHP file in a folder above public_html (so it’s not accessible by the public) and setup a cronjob to execute this code once every hour for each mailbox that I use on my BlackBerry. This prevents the mailbox from filling up as it deletes the trash every hour and doesn’t require me to check it every so often. :)
Filed under: php, site, tutorial — Tags: blackberry, code, device, email, mail, mobile, php, site, tutorial —