2011年2月17日 星期四

[PHP] 刪除路徑下所有檔案與目錄, 模擬 rm -rf

當你php 無法執行 exec('rm -rf') 指令去刪除目錄下所有檔案與目錄時, 只好靠程式啦~

$log = '/home/logs/2011';
SureRemoveDir($log , true); // 第二個參數: true 連 2011 目錄也刪除
function SureRemoveDir($dir, $DeleteMe) {
if(!$dh = @opendir($dir)) return;
while (false !== ($obj = readdir($dh))) {
if($obj=='.' || $obj=='..') continue;
if (!@unlink($dir.'/'.$obj)) SureRemoveDir($dir.'/'.$obj, true);
}
if ($DeleteMe){
closedir($dh);
@rmdir($dir);
}
}

來源:PHP官網

【下列文章您可能也有興趣】

沒有留言: