我使用 Codeigniter 的上传类将图像上传到项目中的文件夹。在数据库中我只存储上传图片后生成的url,所以当我想删除数据库中的一行时,我还需要删除图片。我怎样才能在codeigniter中做到这一点?
我将不胜感激您的回答。
我使用 Codeigniter 的上传类将图像上传到项目中的文件夹。在数据库中我只存储上传图片后生成的url,所以当我想删除数据库中的一行时,我还需要删除图片。我怎样才能在codeigniter中做到这一点?
我将不胜感激您的回答。
您可以使用此功能删除给定路径中的所有文件,例如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';
}
}
delete_row_from_db(); unlink('/path/to/file');
/path/to/file 必须是真实路径。
例如:
如果您的文件夹是这样的 htp://example.com/uploads
$path = realpath (APPPATH . '../uploads');
APPPATH = 应用程序文件夹的路径。
它的工作...
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'];
}
}
$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);
}
看法:
<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'];
}
}
尝试使用delete_files('path')
CI 框架本身提供的功能:
https ://ellislab.com/codeigniter/user-guide/helpers/file_helper.html
$image_data = $this->upload->data();
unlink($image_data['full_path']);
此行将$this->upload->data()
返回有关上传文件的许多信息。您可以打印信息并相应地工作。