CI-file upload, error-showing-if/else causes image duplication - codeigniter

I had somehow managed to upload and resize multiple images, everything was fine.
Then i wanted to show errors if no image was selected to upload.
I put a if statement to load the error but that's causing a havoc.
Each time i select images and upload, the last one gets duplicated, without resizing.
Again, if i remove the if else, it's perfectly fine.
Thankyou for any help and your time.
function do_upload(){
$path = array();
$count = count($_FILES['userfile']['size']);
foreach($_FILES as $key=>$value){
for($n=0; $n<=$count-1; $n++) {
$_FILES['userfile']['name']=$value['name'][$n];
$_FILES['userfile']['type'] = $value['type'][$n];
$_FILES['userfile']['tmp_name'] = $value['tmp_name'][$n];
$_FILES['userfile']['error'] = $value['error'][$n];
$_FILES['userfile']['size'] = $value['size'][$n];
$config['upload_path'] = './images';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$this->load->library('upload', $config);
$this->upload->do_upload();
$data = $this->upload->data();
$path[] = $data['full_path'];
}
if(!$this->upload->do_upload()){
$error = array('error' => $this->upload->display_errors());
$this->load->view('view_dashboard_error_car', $error);
}
else{
$this->load->library('image_lib');
foreach($path as $p=>$ath){
$config1 = array(
'source_image' => $ath,
'new_image' => './images',
'maintain_ration' => true,
'overwrite' => true,
'width' => 600,
'height' => 400
);
$this->image_lib->initialize($config1);
$this->image_lib->resize();
$this->image_lib->clear();
}
$this->load->view('view_dashboard_success_car');
}
}
}

You're running $this->upload->do_upload() twice, because your foreach() runs and then your if/else statement runs.
You need to put the if/else into your foreach loop. You should take care not to just copy/paste it in, but make sure you're only running $this->upload->do_upload() once per image.

Related

Upload an image to two different paths

How to upload an image and save it in two different folders, ./imgup/web/data_dinamis/ and ./imgup/web/video/ ?
My code to upload image :
$config['upload_path'] = './imgup/web/data_dinamis/';
$config['upload_path'] = './imgup/web/video/';
$config['allowed_types'] = '*';
$config['file_name'] = $nama_baru;
$this->load->library('upload',$config);
$this->upload->do_upload('file');
$this->upload->display_errors();
$berita = array(
'user_id' => $this->session->userdata('user')->user_id,
'kategori_id' => $this->input->post('kategori_id'),
'judul' => $this->input->post('judul'),
'gambar' => $nama_baru,
);
All images are saved only in './imgup/web/data_dinamis/', but not in './imgup/web/video/'.
the easiest would be to use ->do_upload() for each of the path you might want to upload to:
$p1='./imgup/web/data_dinamis/';
$p2='./imgup/web/video/';
//create an array of pathes:
$p=array($p1, $p2);
// get length of array
$c=count($p);
// loop through
for ($i=0;$i<$c;$i++){
$config['upload_path'] =$p[$i];
$config['allowed_types'] = '*';
$config['file_name'] = $nama_baru;
$this->load->library('upload',$config);
$this->upload->initialize($config);
$this->upload->do_upload('file');
$this->upload->display_errors();
}
$berita = array(
'user_id' => $this->session->userdata('user')->user_id,
'kategori_id' => $this->input->post('kategori_id'),
'judul' => $this->input->post('judul'),
'gambar' => $nama_baru,
);
note: after $this->load->library('upload',$config); use $this->upload->initialize($config);
This is useful if you auto-load the class, see docs here

Codeigniter Single Image into Multiple Resize ie 350*250, 50*50 and original size

I am new to CodeIgniter. This is what I want to do:
Resize the product image into 350*250, 50*50 and origional image while uploading the image in add product from admin.
All these three images in the three different folders.
Here is my code-
public function products()
{
$config=array();
$config['upload_path']="./uploads/";
$config['allowed_types']="jpg|jpeg|gif|png";
$this->load->library('upload',$config);
$this->upload->initialize($config);
if ( ! $this->upload->do_upload('userfile'))
{
$error = array('error' => $this->upload->display_errors());
}
else
{
$file_data = $this->upload->data();
$data1['img']=base_url().'images/'.$file_data['file_name'];
$data_image = array(
'agenda_id' => $this->input->post('agenda_id'),
'file' => $file_data['file_name']
);
$config['image_library']='gd2';
$config['source_image']='./uploads/'.$file_data["file_name"];
$config['create_thumb']=FALSE;
$config['maintain_ratio']=FALSE;
$config['quality']='60%';
$config['width']=350;
$config['height']=250;
$config['new_image']='./uploads350/'.$file_data["file_name"];
$this->upload->initialize($config);
$this->load->library('image_lib',$config);
$this->image_lib->resize();
}
$this->load->model("Admin_model");
$data= array(
"Type" =>$this->input->post("Type"),
"Brand" =>$this->input->post("Brand"),
"Product_Name" =>$this->input->post("Product_Name"),
"Price" =>$this->input->post("Price"),
"Image"=>$data_image['file']
);
$this->Admin_model->admin($data);
$this->session->set_flashdata('message', 'Product added successfully');
redirect('Admin/product_list');
}
This should work fine (haven't tested). Just make sure the folders exist. Also, if I were you I'd probably keep everything in the same folder and just prepend the size afterwords like some_image_50.jpg:
public function products() {
$config = array();
$config['upload_path'] = "./uploads/";
$config['allowed_types'] = "jpg|jpeg|gif|png";
$this->load->library('upload', $config);
$this->upload->initialize($config);
if (!$this->upload->do_upload('userfile')) {
$error = array('error' => $this->upload->display_errors()); // do something with this...
// e.g. show_error($this->upload->display_errors());
} else {
$file_data = $this->upload->data();
$data1['img'] = base_url() . 'images/' . $file_data['file_name'];
$data_image = array(
'agenda_id' => $this->input->post('agenda_id'),
'file' => $file_data['file_name']
);
//$config['image_library'] = 'gd2'; (default; not needed)
$this->load->library('image_lib');
$cfg['source_image'] = './uploads/' . $file_data["file_name"];
$cfg['create_thumb'] = FALSE;
$cfg['maintain_ratio'] = FALSE;
$cfg['quality'] = '60%';
$cfg['width'] = 350;
$cfg['height'] = 250;
$cfg['new_image'] = './uploads350/' . $file_data["file_name"];
//$this->upload->initialize($config); why??
$this->image_lib->initialize($cfg);
$this->image_lib->resize();
// the following vars will override certain vars above and keep the ones we haven't overridden
$cfg['width'] = 50;
$cfg['height'] = 50;
$cfg['new_image'] = './uploads50/' . $file_data["file_name"]; // make sure folder exists
$this->image_lib->initialize($cfg);
$this->image_lib->resize();
}
$this->load->model("Admin_model");
$data = array(
"Type" => $this->input->post("Type"),
"Brand" => $this->input->post("Brand"),
"Product_Name" => $this->input->post("Product_Name"),
"Price" => $this->input->post("Price"),
"Image" => $data_image['file']
);
$this->Admin_model->admin($data);
$this->session->set_flashdata('message', 'Product added successfully');
redirect('Admin/product_list');
}

why codeigniter do_upload doesn't work on server?

I have used codeigniter do_upload to upload mp3 files on a directory on server.
my codes work perfectly on localhost but on production server just browser keeps waiting for server and processing and nothing happens after a long time.
$dirpath in following code is the path of destination directory on server.
$data['info']=$this->cp_model->GetInfo($service_id);
$dirpath = '/var/li/sounds/'.$data['info'][0]->path;
$config = array('allowed_types' => 'mp3' ,
'upload_path' => $dirpath,
'overwrite' => FALSE,
'max_size' => 0,
);
$this->load->library('upload',$config);
}
if (isset($_POST['submit'])) {
$this->upload->do_upload();}
Most probably you don't have write permissions on the folder declared on your $dirpath. Also consider that uploading an mp3 that may be 4-5 MB server side, can take some minutes depending your connection.
To find out what your problem is whatsoever, output your error by checking the do_upload() method.
if ( ! $this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload_form', $error);
}
More information on the File Uploading class.
Your script works everywhere beside "Local" server
Now I had the same problem, tested it in Hosting Web Server, and it worked. If u wanna the code, here u are:
public function do_upload()
{
$config['upload_path'] = './img';
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$config['max_size'] = '1000';
$config["encrypt_name"] = true;
$config["remove_spaces"] = true;
$this->load->library('upload', $config);
$this->upload->initialize($config);
if ( ! $this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload_view', $error);
}
else
{
echo "SUCCESS";
}
}

codeigniter update image not reuploading

I'm running over this problem which I was trying for the last few hours
I'm having an image upload with some details to store in db.
I store the details and image path, working like a charm. Now comes the edit part.
I'm trying to check if the input file is empty, if so update just the details, else delete the image and reupload new image. The problem is this:
If the input file is empty it updates everything no problem, if is not empty it is updating the details, but the image is the same, doesn't get deleted or reuploaded.
here is the code
$image_input = $this->input->post('image');
if(isset($image_input) && !empty($image_input))
{
$this->db->where('id', $id);
$img = $this->db->get('menus_category', 1);
if($img->num_rows() > 0)
{
$row = $img->row();
$original_image = $row->image;
$desktop_image = $row->desk_img;
$mobile_image = $row->mob_img;
$thumb_image = $row->thumb;
$unlink_image = unlink('./uploads/menus/' . $original_image);
$unlink_desk = unlink('./uploads/menus/desk/' . $desktop_image);
$unlink_mob = unlink('./uploads/menus/mobile/' . $mobile_image);
$unlink_thumb = unlink('./uploads/menus/thumbs/' . $thumb_image);
if($unlink_desk && $unlink_image && $unlink_mob && $unlink_thumb)
{
$config = array(
'upload_path' => './uploads/menus',
'allowed_types' => 'gif|jpg|jpeg|png',
'max_size' => '15000'
);
$this->upload->initialize($config);
if ($this->upload->do_upload('image'))
{
$image_data = $this->upload->data();
$this->load->library('image_lib');
// thumb resize
$thumbnail = 'thumb_' . $image_data['file_name'];
$thumb = array(
'image_library' => 'GD2',
'source_image' => $image_data['full_path'],
'new_image' => $image_data['file_path'] . 'thumbs/' . $thumbnail,
'maintain_ratio' => TRUE,
'width' => '90',
'height' => '90'
);
$this->image_lib->initialize($thumb);
$this->image_lib->resize();
$this->image_lib->clear();
// mobile resize
$mob = 'mob_' . $image_data['file_name'];
$thumb_mob = array(
'image_library' => 'GD2',
'source_image' => $image_data['full_path'],
'new_image' => $image_data['file_path'] . 'mobile/' . $mob,
'maintain_ratio' => FALSE,
'width' => '290',
'height' => '83'
);
$this->image_lib->initialize($thumb_mob);
$this->image_lib->resize();
$this->image_lib->clear();
// desktop resize
$desk = 'desk_' . $image_data['file_name'];
$thumb_desk = array(
'image_library' => 'GD2',
'source_image' => $image_data['full_path'],
'new_image' => $image_data['file_path'] . 'desk/' . $desk,
'maintain_ratio' => FALSE,
'width' => '700',
'height' => '200'
);
$this->image_lib->initialize($thumb_desk);
$this->image_lib->resize();
$this->image_lib->clear();
// insert path and details to database
$data = array(
'title' => $input['title'],
'slug' => $this->_check_slug($input['title']),
'description' => $input['description'],
'image' => $image_data['file_name'],
'desk_img' => $desk,
'mob_img' => $mob,
'thumb' => $thumbnail
);
$this->db->where('id', $id);
return $this->db->update('menus_category', $data);
}
else
{
echo $this->image_lib->display_errors();
}
}
}
}
else
{
$data2 = array(
'title' => $input['title'],
'slug' => $this->_check_slug($input['slug']),
'description' => $input['description']
);
$this->db->where('id', $id);
return $this->db->update('menus_category', $data2);
}
Note: the else statement works fine, but the first if the problem. Now I changed the if to just if(isset($image_input)) ... and if file input is not empty is reuploading the picture and updating the details fine, but if I update only the details with no picture, it is deleting the picture that is already uploaded and is not updating. (I think this is the problem but I can't figure out how to fix it).
If you will to give me some help or to put me on right direction I will be thankful.
Thanks guys
First, this would be a comment asking a question, but I don't have enough reputation do add one just yet...
If you could post your HTML form, that would be helpful, but without that...
1) I assume the form you are submitting has enctype="multipart/form-data" in the opening tag.
2) On line 2 of your code here, $this->input->post('image'), is 'image' from a form input of type file? If so, your statement won't work as 'image' is part of the $_FILES array and not $_POST anymore. Meaning when you go to check it, it is always going to be empty (or non-existent).
To verify that your form is submitting the way you think it is, do this just before the first line in the code you have in your post:
var_dump($_POST);
var_dump($_FILES);
exit; // don't let anything run after the dumps.
let me know if that puts you in the right direction or not.

error resizeing images in a loop in codeigniter

i have a problem while uploading and resizing images in a loop.
can anyone please provide me the working sample of code of codeigniter for uploading and resizing at the same time in a loop.
I want to upload and resize images uploaded from the form. There will be more than 1 images so i have to upload them in loop.
My code first uploads the image then resizes it. 1ts images is uploaded and resized correctly but during 2nd loop the image is uploaded but not resized. It throws this error:
Your server does not support the GD
function required to process this type
of image.
I have tried the clear function too
$this->image_lib->clear();
can anyone please help
Dont load image_lib multiple times. Add image_lib in autoload libs and change
$this->load->library('image_lib', $config);
to
$this->image_lib->initialize($config);
I had the same problem but this seemed to work:
// Do upload
if (! $this->upload->do_upload($image_name)) {
// return errors
return array('errors' => $this->upload->display_errors());
}
$data = $this->upload->data();
$config_manip = array(
'image_library' => 'gd2',
'source_image' => "./assets/uploads/{$data['file_name']}",
'new_image' => "./assets/uploads/thumbs/{$data['file_name']}",
'create_thumb' => true,
'thumb_marker' => '',
'maintain_ratio' => true,
'width' => 140,
'height' => 140
);
// Create thumbnail
$this->load->library('image_lib');
$this->image_lib->resize();
$this->image_lib->clear();
$this->image_lib->initialize($config_manip);
if ( ! $this->image_lib->resize()){
return array('errors' => $this->image_lib->display_errors());
}
Notice the Create Thumbnail goes:
Load Library,
Resize Image,
CLEAR,
Initialize Config
I was putting the clear after the initialize which was causing the same error you're getting.
Here is a working code from my image gallery controller. This function uploads a batch of images, resizes them and saves them to database.
public function create_photo_batch() {
$this->load->library('image_lib');
$this->load->library('upload');
// Get albums list for dropdown
$this->data['albums'] = $this->gallery_m->get_albums_list();
if(isset($_FILES['images']) && $_FILES['images']['size'] > 0) {
$album_id = $this->input->post('albumid');
$images = array();
$ret = array();
// Upload
$files = $_FILES['images'];
foreach ($files['name'] as $key => $image) {
$_FILES['images[]']['name']= $files['name'][$key];
$_FILES['images[]']['type']= $files['type'][$key];
$_FILES['images[]']['tmp_name']= $files['tmp_name'][$key];
$_FILES['images[]']['error']= $files['error'][$key];
$_FILES['images[]']['size']= $files['size'][$key];
$upload_config = array(
'allowed_types' => 'jpg|jpeg|gif|png',
'upload_path' => realpath(APPPATH . "../uploads/gallery"),
'max_size' => 5000,
'remove_spaces' => TRUE,
'file_name' => md5(time())
);
$this->upload->initialize($upload_config);
if ($this->upload->do_upload('images[]')) {
$image_data = $this->upload->data();
$images[] = $image_data['file_name'];
} else {
$this->session->set_flashdata('error', $this->upload->display_errors() );
redirect('admin/gallery/create_photo_batch');
}
}
// Resize
foreach ($images as $image) {
$resize_config = array(
'source_image' => realpath(APPPATH . '../uploads/gallery') .'/'. $image,
'new_image' => realpath(APPPATH . '../uploads/gallery/thumbs'),
'maintain_ratio' => TRUE,
'width' => 500,
'height' => 500
);
$this->image_lib->initialize($resize_config);
if ( ! $this->image_lib->resize() ) {
echo $this->image_lib->display_errors();
die;
}
$this->image_lib->clear();
}
// Save to db
foreach ($images as $image) {
$ret[] = array(
'AlbumID' => (int) $album_id,
'Url' => $image,
'IsActive' => 1
);
}
$this->gallery_m->save_images($ret);
redirect('admin/gallery/album/'.$album_id);
}
//Load view
$this->data['subview'] = 'admin/gallery/photo_upload_batch_view';
$this->load->view('admin/_layout_main', $this->data);
}
Your error message suggest that it's not the loop that is the problem, but rather that the 2nd file is of a different filetype than the 1st. And that the underlying server don't have the needed libraries (http://www.libgd.org/Main_Page) installed to handle that file type.
$config['image_library'] = 'gd2';
$config['source_image'] = './assets/upload_images/A.jpg';
$config['create_thumb'] = FALSE;
$config['maintain_ratio'] = TRUE;
$config['width'] = 1600;
$config['height'] = 900;
$config['new_image'] = './assets/upload_images/'.$randy;
$this->load->library('image_lib', $config);
$this->image_lib->initialize($config);
$this->image_lib->resize();
$this->image_lib->clear();
I had same problem but solved these by this code.

Resources