如何使用Codeigniter删除上传的文件?

时间:2013-02-15 17:23:24

标签: php codeigniter upload

我使用Codeigniter的Upload Class将图像上传到项目中的文件夹。在数据库中我只存储上传图像后生成的url,所以当我想删除db中的一行时我还需要删除图像。我怎么能在codeigniter中做到这一点?

我将很感激你的答案。

7 个答案:

答案 0 :(得分:10)

您可以使用此uploads函数删除给定路径中的所有文件,例如deleteFiles()文件夹中的文件,该函数可能位于您的某个模型中:

$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';
    }   
}

答案 1 :(得分:3)

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

/ path / to / file必须是真实路径。

例如:

如果你的文件夹是这样的htp://example.com/uploads

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

APPPATH =应用程序文件夹的路径。

它的工作......

答案 2 :(得分:1)

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'];
            }
        } 

答案 3 :(得分:0)

$m_img_real= $_SERVER['DOCUMENT_ROOT'].'/images/shop/real_images/'.$data['settings']->shop_now;
$m_img_thumbs = $_SERVER['DOCUMENT_ROOT'].'/images/shop/thumbs/'.$data['settings']->shop_now;

if (file_exists($m_img_real) && file_exists($m_img_thumbs)) 
{
     unlink($m_img_real);
     unlink($m_img_thumbs);
}

答案 4 :(得分:0)

查看:

<input type="file" name="new_file" data-required="1" class="" />
<input type="hidden" name="old_file" value="echo your old file name"/>
<input type="submit" name="submit"/>

控制器:

function edit_image() {

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

                move_uploaded_file($_FILES['new_file']['tmp_name'],'./public_html/banner/'.$_FILES['new_file']['name']);

                $upload = $_FILES['new_file']['name'];

                $name = $post['old_file'];
                @unlink("./public_html/banner/".$name);
            }
            else {

                $upload = $post['old_file'];
            }              

}

答案 5 :(得分:0)

尝试使用CI框架本身提供的delete_files('path')功能: https://ellislab.com/codeigniter/user-guide/helpers/file_helper.html

答案 6 :(得分:0)

$image_data = $this->upload->data();
unlink($image_data['full_path']);

此行$this->upload->data()将返回有关上传文件的许多信息。您可以打印信息并相应地工作。