How to delete uploaded files with Codeigniter?

43,300

Solution 1

You can delete all the files in a given path, for example in the uploads folder, using this deleteFiles() function which could be in one of your models:

$path = $_SERVER['DOCUMENT_ROOT'].'/uploads/';

function deleteFiles($path){
    $files = glob($path.'*'); // get all file names
    foreach($files as $file){ // iterate files
      if(is_file($file))
        unlink($file); // delete file
        //echo $file.'file deleted';
    }   
}

Solution 2

delete_row_from_db(); unlink('/path/to/file');

/path/to/file must be real path.

For eg :

if your folder is like this htp://example.com/uploads

$path = realpath(APPPATH . '../uploads');

APPPATH = path to the application folder.

Its working...

Solution 3

if(isset($_FILES['image']) && $_FILES['image']['name'] != '') {

            $config['upload_path']   = './upload/image'; 
            $config['allowed_types'] = 'jpeg|jpg|png';
            $config['file_name']    = base64_encode("" . mt_rand());
            $this->load->library('upload', $config);

            $this->upload->initialize($config); 

            if (!$this->upload->do_upload('image')) 
            {
                $error = array('error' => $this->upload->display_errors());
                $this->session->set_flashdata('msg', 'We had an error trying. Unable upload  image');
            } 
            else 
            { 
                $image_data = $this->upload->data();
                @unlink("./upload/image/".$_POST['prev_image']);
                $testData['image'] = $image_data['file_name'];
            }
        } 
Share:
43,300
user2065593
Author by

user2065593

Updated on August 25, 2020

Comments

  • user2065593
    user2065593 almost 4 years

    I used the Codeigniter's Upload Class to upload images to a folder in the project. In the database I only store the the url generated after upload the image, so when I want to delete a row in the db I also need to delete the image. How can I do it in codeigniter?

    I will be grateful for your answers.