简体   繁体   中英

Recursively deleting a directory fails after zipping and downloading its contents

I followed this SO thread to recursively delete a directory (see code below). The problem is I can't get these commands to do their things after I have zipped the directory's contents and downloaded the zip file.

File/folder permissions don't appear to be the issue because as I said the code works just fine if folder zipping isn't involved.

Anyone have any ideas?

$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); 

I faced the same issue and found the solution.

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');

This worked for me.

To recursively remove a directory, you can use this code.
NOTE: $var can be a file or directory. If it is a directory, all contents and the directory are deleted.
Source: http://php.net/manual/en/function.rmdir.php , look at the comment by jurchiks101 at gmail dot com.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM