簡體   English   中英

在壓縮並下載目錄內容后,遞歸刪除目錄失敗

[英]Recursively deleting a directory fails after zipping and downloading its contents

我按照此SO線程遞歸刪除目錄(請參見下面的代碼)。 問題是我壓縮目錄的內容並下載了zip文件后,無法使這些命令執行其操作。

文件/文件夾權限似乎不是問題所在,因為正如我所說,如果不涉及文件夾壓縮,代碼就可以正常工作。

有人有想法么?

$this->zip->download($file_name); //a Codeigniter function, though think it could be any function that executes the zip file download.

$dir='uploads/folder1'; 
//the contents of folder1 are "foo1.png" and "foo2.png"

$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS),  RecursiveIteratorIterator::CHILD_FIRST);

foreach ($files as $fileinfo) {
    $todo = ($fileinfo->isDir() ? 'rmdir' : 'unlink');
    $todo($fileinfo->getRealPath());
}

rmdir($dir); 

我遇到了同樣的問題並找到了解決方案。

protected function _deleteFolder($path = null) {

    if (!$path || !file_exists($path)) {
        return FALSE;
    }

    delete_files($path, true); // delete all files/folders
    rmdir($path);
}

$folder_path = '/path/to/the/folder/to/be/zipped/downloaded';
$this->zip->read_dir($folder_path, FALSE);
$this->_deleteFolder($folder_path); // This will delete the folder
$this->zip->download('zipped-downloadable-file-name.zip');

這對我有用。

要遞歸刪除目錄,可以使用此代碼。
注意: $ var可以是文件或目錄。 如果是目錄,則將刪除所有內容和目錄。
來源: http ://php.net/manual/en/function.rmdir.php,請看jurchiks101在gmail點com上的評論。

if(file_exists($var))
{
    if (PHP_OS === 'Windows')
    {
        exec("rd /s /q {$var}");
    }
    else
    {
        exec("rm -rf {$var}");
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM