简体   繁体   中英

Codeigniter delete the directory and its contents

I am trying to make codeigniter delete a product image folder.

Furthermore, the delete function I am trying to make needs to delete also all of its contents, so empty or not, the folder gets deleted. I'm guessing, it would use a recursive type of deletion...I'm not so sure at all.

I have tried the below functions for deleting :

function delete_directory($path)
{
    $path=base_url().'products/thumb/';
    $this->load->helper("file"); // load the helper
    delete_files($path, true); // delete all files/folders
     //rmdir($dirname);
     if(rmdir($path)){
        echo 'deleted';die;}
     else{
        echo 'not';die; }
     return true;

}

But it always returning not

Deleting directory content: It will probably work, I have used

$this->load->helper('directory');
$this->load->helper("file");

$dir_fiels = directory_map('resources/captcha/');
$len = sizeOf($dir_fiels);
for($i=0; $i<$len;$i++){
    unlink('resources/captcha/'.$dir_fiels[$i]);
}

create an helper. see below:-

<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

if ( ! function_exists('remove_directory'))
{
function remove_directory($directory, $empty=FALSE)
{
    if(substr($directory,-1) == '/') {
        $directory = substr($directory,0,-1);
    }

    if(!file_exists($directory) || !is_dir($directory)) {
        return FALSE;
    } elseif(!is_readable($directory)) {

    return FALSE;

    } else {

        $handle = opendir($directory);
        while (FALSE !== ($item = readdir($handle)))
        {
            if($item != '.' && $item != '..') {
                $path = $directory.'/'.$item;
                if(is_dir($path)) {
                    remove_directory($path);
                }else{
                    unlink($path);
                }
            }
        }
        closedir($handle);
        if($empty == FALSE)
        {
            if(!rmdir($directory))
            {
                return FALSE;
            }
        }
    return TRUE;
    }
}
}

then load this helper in Your controller and call function remove_directory()

/* End of file recursive_helper.php */
/* Location: /application/helpers/recursive_helper.php */ 

Delete all files:

  delete_files('./path/to/your/directory/');

Include sub-folder(s):

  delete_files('./path/to/your/directory/', TRUE);

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