How to delete uploaded files with Codeigniter? - php

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.

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

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...

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

View:
<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"/>
Controller:
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'];
}
}

Try using delete_files('path') function offered by CI framework itself:
https://ellislab.com/codeigniter/user-guide/helpers/file_helper.html

$image_data = $this->upload->data();
unlink($image_data['full_path']);
This line $this->upload->data() will return many information about uploaded file. You can print information and work accordingly.

Related

How to delete old images from uploads folder after inserting insert a new image

I am able to overwrite the image in the database but the old images still remains in the assets folder.
How can I delete the previous image from the assests folder when i insert a new one?
Please explain in a bit of details since i am a beginner.
public function image_insert(){
$id=1;
if ($this->input->post('submit') && !empty($_FILES['body_image']['name'])) {
$body_image = $_FILES['body_image']['name'];
if($body_image != NULL){
$config['upload_path'] = './assets/image/';
$config['log_threshold'] = 1;
$config['allowed_types'] = 'jpg|png|jpeg|gif';
$config['max_size'] = '0'; // 0 = no file size limit
$config['overwrite'] = true;
$this->load->library('upload', $config);
$this->upload->do_upload('body_image');
$upload_data = $this->upload->data();
$body_image = $upload_data['file_name'];
}
$this->Home_model->insert_image($body_image,$id);
redirect(base_url('landing_page/home_edit'));
}
else {
redirect(base_url('landing_page/home_edit'));
}
}
If you want to delete a file which already exists in your image folder.
Suppose your image folder path is: /assets/image/
Then, the image delete code will be something like this.
$filePath="/assets/image/";
$fileName=$filePath."dummy.jpg";
if (file_exists($fileName))
{
unlink($fileName);
}
The above code will call you before uploading the image in upload folder.
you may use File helper to delete file :-
$this->load->helper('file');
$path='./assets/image/'.$file_name;
delete_files($path);

Dynamically Codeigniter Image Upload Rename

I am uploading multiple dynamic images with codeigniter with the following code.
foreach ($_FILES as $key => $value) {
$imagePrefix = time();
if (!$this->upload->do_upload($key))
{
echo $errors = $this->upload->display_errors();
return '';
}
else
{
$imagename = $imagePrefix.$value['name'];
$insertImage = $this->db->query("Insert into `tbl_event_imges` (`iEventID`,`vImage`) values ('".$insertId."','".$imagename."')");
}
}
When I upload an image to the specific folder this works fine; the issue is if a user uploads an image having same name, then it will automatically rename the image and upload to the folder, but what I want is to rename it by adding $imagePrefix that I have added in else part of the code and then want to upload the image with this name. But this is not working with me..
Any suggestion please?
you need to provide configuration preferences to your upload function like so:
$imagePrefix = time();
$imagename = $imagePrefix.$value['name'];
$this->load->library('upload');
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['file_name'] = $imagename; // set the name here
$this->upload->initialize($config);
if (!$this->upload->do_upload($key)){
...
}else{
...
}
Source: http://www.codeigniter.com/user_guide/libraries/file_uploading.html?highlight=file%20upload#setting-preferences
Just alternative, you can use CI's rename function to rename after file uploaded.
$image = $this->upload->data();
$file_path = $image ['file_path'];
$file = $image ['full_path'];
$file_ext = $image['file_ext'];
$final_file_name = time() . $image['file_name'] . $file_ext;
only add below code and it run successfully and also set encrypt_name to false
$path = $_FILES['userfile']['name'];
$newName = "Add any name".".".pathinfo($path, PATHINFO_EXTENSION);
$config['file_name'] = $newName;
$config['encrypt_name'] = false;

Can I upload file with this code in codeigniter?

$judul = $_POST['judul'];
$idKategori = $_POST['kategori'];
$idPropinsi = $_POST['propinsi'];
$img = $_FILES['img']['name'];
$img_tmp = $_FILES['img']['tmp_name'];
$idUser = $_POST['user'];
$isi = $_POST['isi'];
$date = $_POST['date'];
if(empty($img)) {
$query = mysql_query("INSERT INTO `artikel`(`idArtikel`, `idKategori`, `idPropinsi`, `judul`, `idUser`, `isi`, `date`) VALUES ('','$idKategori','$idPropinsi','$judul','$idUser','$isi','$date')");
}else{
if(move_uploaded_file($img_tmp,"../../../img/".$img)) {
$query = mysql_query("INSERT INTO `artikel`(`idArtikel`, `idKategori`, `idPropinsi`, `judul`, `img`, `idUser`, `isi`, `date`) VALUES ('','$idKategori','$idPropinsi','$judul','$img','$idUser','$isi','$date')");
}else{
echo "Failed to upload image";
}
}
if($query) {
header("location:../../index.php?page=artikel");
}else{
echo "failed to update this post";
}
But the result is
move_uploaded_file(http://localhost/mvc/kuliner/assets/img/Green Nature Wallpapers 04.jpg): failed to open stream: HTTP wrapper does not support writeable connections
No!
Basically rewriting this code to work with Codeigniter is a lot more work than writing it from scratch using examples found in the CI documentation. Link provided in comment above (http://www.codeigniter.com/userguide2/libraries/file_uploading.html).
There are several reasons as both file upload, redirection, database handling, user output etcetera are done differently in CI using CI's methods and the MVC structure of programming.
This is how I do my uploads in CI (Using Dropzone).
Create Dropzone Controller
class Dropzone extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->helper(array('url','html','form'));
}
public function upload() {
if (!empty($_FILES)) {
$tempFile = $_FILES['file']['tmp_name'];
$temp = $_FILES["file"]["name"];
$path_parts = pathinfo($temp);
$t = preg_replace('/\s+/', '', microtime());
$fileName = $path_parts['filename']. $t . '.' . $path_parts['extension'];
$targetPath = UPLOADPATH;
$targetFile = $targetPath . $fileName ;
echo $fileName;
move_uploaded_file($tempFile, $targetFile);
// if you want to save in db,where here
// with out model just for example
// $this->load->database(); // load database
// $this->db->insert('file_table',array('file_name' => $fileName));
}
}
}
// Usage : <form action="<?php echo site_url('/dropzone/upload');" class="dropzone" >
/* End of file dropzone.js */
/* Location: ./application/controllers/dropzone.php */
Secondly Add the following HTML, (mainly to a form so as to submit file name
<div id="upload" class="form-group">
<label>Drop file Here</label>
<input type="hidden" id="file" name="file"/>
<div
class="dropzone"
id="uploadFile"><!--uploadFile is the dropzone name-->
</div>
</div>
Then a little Js to do the magic
Dropzone.options.uploadFile = {
paramName: "file", // The name that will be used to transfer the file
url:"<?php echo site_url('/dropzone/upload');?>",
maxFiles:1,
acceptedFiles:'image/*,application/pdf,.docx,.doc,.xls,.xlsx,.csv',
dictMaxFilesExceeded:"You can only upload one file per Response",
init: function() {
this.on("sending", function(file) {
// $('button#submit').attr('disabled','');// Requires Jquery
});
this.on("complete", function(file) {
//$('button#submit').removeAttr('disabled'); // Requires JQuery
});
this.on("success", function(file,xhr) {
//$('input[type="hidden"]#file').val(xhr); // Requires Jquery
});
}
};
Remember to include dropzone.js and jquery.js if needed.
You can upload files using the PHP function. But at first, you should make the directory or folder by yourself.
Here is my code, I did not add the validation part. I have created the uploads folder in the root directory.
$file = $_FILES['verfication_image'];
$file_name_with_extenstion = $file['name'];
$file_name = pathinfo($file_name_with_extenstion, PATHINFO_FILENAME);
$extension = pathinfo($file_name_with_extenstion, PATHINFO_EXTENSION);
$file_tmp_location =$_FILES['verfication_image']['tmp_name'];
$upload_name = $file_name.time().".$extension";
if(move_uploaded_file($file_tmp_location,"uploads/".$upload_name)){
echo "The file has been uploaded.";
}else{
echo "There was an error.";
}
I would suggest using the Codeigniter version of uploading the file as it is simple to add validation. I have added my Codeigniter code with validation,
$file = $_FILES['verfication_image'];
$file_name_with_extenstion = $file['name'];
$file_name = pathinfo($file_name_with_extenstion, PATHINFO_FILENAME);
$extension = pathinfo($file_name_with_extenstion, PATHINFO_EXTENSION);
$upload_name = $file_name.time().".$extension";
$config['upload_path'] = 'uploads/';
$config['file_name'] = $upload_name;
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 1024;
$config['max_width'] = 1024;
$config['max_height'] = 768;
$this->load->library('upload', $config);//Load the libary with the configuration
if(!$this->upload->do_upload('verfication_image')){
echo($this->upload->display_errors());//validation error will be printed
}else{
echo "The file has been uploaded.";
}
For more details, please follow the official guideline File Uploading class

Codeigniter, how to save uploaded file to new folder?

I'm adding onto an admin CMS, and need image files uploaded to save to a separate folder I have specified. I can save them to a predefined folder of another controller, but how do I save them to the new folder I have created?
When I try, it doesn't allow it. I know it has something to do with routing, but where to I change codeigniter to allow that? I have looked in config/routes.php and don't see it listed there.
Thank you!
you can try this
function uploadFile($uploadFile,$filetype,$folder,$fileName='')
{
$resultArr = array();
$config['max_size'] = '1024000';
if($filetype == 'img') $config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['upload_path'] = './uploads/'.$folder.'/';
if($fileName != "")
$config['file_name'] = $fileName;
$this->load->library('upload', $config);
$this->upload->initialize($config);
if(!$this->upload->do_upload($uploadFile))
{
$resultArr['success'] = false;
$resultArr['error'] = $this->upload->display_errors();
} else {
$resArr = $this->upload->data();
$resultArr['success'] = true;
$resultArr['path'] = "uploads/".$folder."/".$resArr['file_name'];
}
return $resultArr;
}

how to unzip uploaded zip file?

I am trying to upload a zipped file using codeigniter framework with following code
function do_upload()
{
$name=time();
$config['upload_path'] = './uploadedModules/';
$config['allowed_types'] = 'zip|rar';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload_view', $error);
}
else
{
$data = array('upload_data' => $this->upload->data());
$this->load->library('unzip');
// Optional: Only take out these files, anything else is ignored
$this->unzip->allow(array('css', 'js', 'png', 'gif', 'jpeg', 'jpg', 'tpl', 'html', 'swf'));
$this->unzip->extract('./uploadedModules/'.$data['upload_data']['file_name'], './application/modules/');
$pieces = explode(".", $data['upload_data']['file_name']);
$title=$pieces[0];
$status=1;
$core=0;
$this->addons_model->insertNewModule($title,$status,$core);
}
}
But the main problem is that when extract function is called, it extract the zip but the result is empty folder. Is there any way to overcome this problem?
$zip = new ZipArchive;
$res = $zip->open($fileName);
if($res==TRUE)
{
$zip->extractTo($path.$fileName);
echo "<pre>";
print_r($zip);//to get the file type
$zip->close();
try this :
<?php
exec('unzip filename.zip');
?>
Hmm.., I think you set an incorrect path of your uploaded zip file OR your destination path ('./application/modules/') is incorrect.
Try this :
$this->unzip->extract($data['upload_data']['full_path'], './application/modules/');
I use this -> $data['upload_data']['full_path'], to make sure that it's a real path of the uploaded file.
Hope it helps :)
same problem i faced few min back.if you observe carefully you find
please copy zip file and paste to folder contain programe file(.php) after that you
i think file is not store in temp folder.
if(preg_match("/.(zip)$/i", $fileName))
{
$moveResult= move_uploaded_file($fileTmpLoc, $fileName);
if($moveResult == true)
{
$zip = new ZipArchive;
$res = $zip->open($fileName);
if($res==TRUE)
{
$zip->extractTo($path.$fileName);
echo "<pre>";
print_r($zip);
$zip->close();
} else {
echo 'failed';
}
}
unlink($fileName); // Remove the uploaded file from the PHP temp folder
//exit();
}`
class Upload extends CI_Controller {
function __construct(){
parent::__construct();
// load ci's Form and Url Helpers
$this->load->helper(array('form', 'url'));
}
function index(){
$this->load->view('upload_form_view', array('error' => ' ' ));
}
function file_upload(){
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'zip';
$config['max_size'] = '';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload()){
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload_form_view', $error);
}else{
$data = array('upload_data' => $this->upload->data());
$zip = new ZipArchive;
$file = $data['upload_data']['full_path'];
chmod($file,0777);
if ($zip->open($file) === TRUE) {
$zip->extractTo('./uploads/');
$zip->close();
echo 'ok';
} else {
echo 'failed';
}
$this->load->view('upload_success_view', $data);
}
}
}
In case anyone comes here for same question, just add chmod($file,0777); to the original code posted yetAnotherSE. That solves the issue of empty files.

Categories