Upload multiple File in codeigniter After Submit form - php

In my CodeIgniter project, I'm uploading multiple files during the project creation. Please let me know how to upload multiple file using CI.
This is output array after submit form.
[user_attached] => Array
(
[name] => Array
(
[pic_passport] => cp-user-error.png
[att_document] => local-delivery-done.png
)
[type] => Array
(
[pic_passport] => image/png
[att_document] => image/png
)
[tmp_name] => Array
(
[pic_passport] => C:\xampp\tmp\phpC707.tmp
[att_document] => C:\xampp\tmp\phpC718.tmp
)
[error] => Array
(
[pic_passport] => 0
[att_document] => 0
)
[size] => Array
(
[pic_passport] => 635392
[att_document] => 36512
)
)

To Upload Multiple File in Codeigniter. Try this.
$filesCount = count($_FILES['user_attached']['name']);
$path = 'upload/document';
if (!file_exists($path)) {
mkdir($path, 0777, true);
}
$array = ['pic_passport','att_document'];
for($i = 0; $i < $filesCount; $i++) {
$_FILES['userFile']['name'] = $_FILES['user_attached']['name'][$array[$i]];
$_FILES['userFile']['name'] = $_FILES['user_attached']['name'][$array[$i]];
$_FILES['userFile']['type'] = $_FILES['user_attached']['type'][$array[$i]];
$_FILES['userFile']['tmp_name'] = $_FILES['user_attached']['tmp_name'][$array[$i]];
$_FILES['userFile']['error'] = $_FILES['user_attached']['error'][$array[$i]];
$_FILES['userFile']['size'] = $_FILES['user_attached']['size'][$array[$i]];
$imagename = $this->randomAlphanumId(10);
$image_name[$array[$i]]="doc_".$imagename."_".str_replace(array(' '),'_',$_FILES['userFile']['name']);
$config['upload_path'] = $path;
$config['allowed_types'] = '*';
$config['file_name'] = $image_name[$array[$i]];
$this->load->library('upload',$config);
$this->upload->initialize($config);
if($this->upload->do_upload('userFile')) {
$fileData = $this->upload->data();
$upload_image[] = $fileData['file_name'];
}
}

Create library for this code and call from controller
for($i = 0; $i < $config_array['files_count']; $i++)
{
if($config_array['file_data']['name'][$i])
{
$file_name = $config_array['file_data']['name'][$i];
$file_info = pathinfo($file_name);
$new_file_name = preg_replace('/[[:space:]]+/', '_', $file_info['filename']);
$new_file_name = $new_file_name.'_'.DATE(UPLOAD_FILE_DATE_FORMAT);
$new_file_name = str_replace('.','_',$new_file_name);
$file_extension = $file_info['extension'];
$new_file_name = $new_file_name.'.'.$file_extension;
$_FILES['attchment']['name'] = $new_file_name;
$_FILES['attchment']['tmp_name'] = $config_array['file_data']['tmp_name'][$i];
$_FILES['attchment']['error'] = $config_array['file_data']['error'][$i];
$_FILES['attchment']['size'] = $config_array['file_data']['size'][$i];
$config['upload_path'] = $config_array['file_upload_path'];
$config['file_name'] = $new_file_name;
$config['allowed_types'] = $config_array['file_permission'];
$config['file_ext_tolower'] = TRUE;
$config['remove_spaces'] = TRUE;
$config['max_size'] = $config_array['file_size'];
$this->CI->load->library('upload',$config);
$this->CI->upload->initialize($config);
if($this->CI->upload->do_upload('attchment'))
{
array_push($file_array,array(
'og_name'=> $file_name,
'name'=> $new_file_name)
);
}
else
{
array_push($error_msgs,$this->CI->upload->display_errors('',''));
}
}
}

Related

Codeigniter:Update Image and Display Current image if I don't want to update

I'm stuck on a problem with updating image. I've created image upload which works fine but I also want it to be updated. When I add a need image it updates correctly but I if don't want to change the image and leave it as it is, then my current image can't be retrieve. Please help me
Here is my code:
Controller:
function edit_product($product_id)
{
$data = array('recipe_info' => $this->products_model->getRcipe($this->uri->segment(3)),
'product_id' => $this->uri->segment(3)
);
/*var_dump($data); die();*/
$this->load->view('edit_product', $data);
}
public function save_edit_recipe()
{
$thumnail="";
$stats = "";
$msg = "";
$filename = 'r_image';
$data = array(
'recipe_id' => $this->uri->segment(3),
'r_name' => $this->input->post('r_name'),
'r_image' => '',
'r_description' => $this->input->post('r_description'),
'time_id' => $this->input->post('cooking_time'),
'r_cal' => $this->input->post('calories'),
'r_serve' => $this->input->post('serving_size'),
'r_procedure' => $this->input->post('recipe_procedure')
);
$recipe_id = $this->products_model->update_product($this->uri->segment(3), $data);
foreach($this->input->post('ingredients') as $key => $value)
{
$menuData[] = array('recipe_id' => $this->input->post('recipe_id'),
'ingredient_id' => $value,
'category_id' => $this->input->post('recipe_category')
);
}
$this->products_model->saveMenu($menuData);
$config['upload_path'] = 'img/recipes/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 1024 * 8 ;
$config['encrypt_name'] = true;
$this->load->library('upload',$config);
if (!$this->upload->do_upload($filename))
{
$stats = 'error';
$msg = $this->upload->display_errors('', '');
}else{
$uploadData = $this->upload->data('file_name');
if($uploadData['file_name'])
{
$thumnail = 'img/recipes/'.$uploadData['file_name'];
}else{
$thumnail = 'No thumnbail uploaded!';
}
$updateThumbData = array('recipe_id' => $this->input->post('recipe_id'),
'r_image' => $thumnail
);
$this->products_model->updataRecipeThumnail($updateThumbData);
}
redirect('dashboard');
}
Model:
function getRcipe($recipe_id)
{
$this->db->where('recipe_id', $recipe_id);
$query = $this->db->get('recipe');
return $query->result();
}
public function update_product($product_id, $data)
{
$this->db->where('recipe_id', $product_id);
$this->db->update('recipe', $data);
}
public function updataRecipeThumnail($data)
{
$this->db->where('recipe_id', $data['recipe_id']);
$this->db->update('recipe', $data);
}
i have updated in your script...please used this function... then your problem may be shortout..
public function save_edit_recipe()
{
$thumnail="";
$stats = "";
$msg = "";
$filename = 'r_image';
$data = array(
'recipe_id' => $this->uri->segment(3),
'r_name' => $this->input->post('r_name'),
'r_description' => $this->input->post('r_description'),
'time_id' => $this->input->post('cooking_time'),
'r_cal' => $this->input->post('calories'),
'r_serve' => $this->input->post('serving_size'),
'r_procedure' => $this->input->post('recipe_procedure')
);
$recipe_id = $this->products_model->update_product($this->uri->segment(3), $data);
foreach($this->input->post('ingredients') as $key => $value)
{
$menuData[] = array('recipe_id' => $this->input->post('recipe_id'),
'ingredient_id' => $value,
'category_id' => $this->input->post('recipe_category')
);
}
$this->products_model->saveMenu($menuData);
$config['upload_path'] = 'img/recipes/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 1024 * 8 ;
$config['encrypt_name'] = true;
$this->load->library('upload',$config);
if (!$this->upload->do_upload($filename))
{
$stats = 'error';
$msg = $this->upload->display_errors('', '');
}else{
$uploadData = $this->upload->data('file_name');
if($uploadData['file_name'])
{
$thumnail = 'img/recipes/'.$uploadData['file_name'];
$updateThumbData = array(
'recipe_id' => $this->input->post('recipe_id'),
'r_image' => $thumnail
);
$this->products_model->updataRecipeThumnail($updateThumbData);
}else{
$thumnail = 'No thumnbail uploaded!';
}
}
redirect('dashboard');
}

CodeIgniter Insert query makes extra entry with 0 values

When I trying to insert some values, MySQL shows double entry. The first entry is correct, but second entry contains only zeros. Kindly help me..
My Controller codes are here:
$config['upload_path'] = './img/trainees/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '200';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$this->load->library('upload', $config);
$imgname ='';
if($this->upload->do_upload())
{
$data = $this->upload->data();
$imgname = $data['raw_name'].$data['file_ext'];
}
Above code is used to upload images in controller..
Remaining codes:
$this->load->model('newmodel');
$this->newmodel->NAME = $this->input->post("name");
$this->newmodel->AGE = $this->input->post("age");
$this->newmodel->PLACE = $this->input->post("place");
$this->newmodel->ADDRESS = $this->input->post("address");
$this->newmodel->PHONE = $this->input->post("phone");
$this->newmodel->MAIL = $this->input->post("email");
$this->newmodel->QUALI = $this->input->post("qualification");
$this->newmodel->OCCUP = $this->input->post("occupation");
$this->newmodel->MILMAID = $this->input->post("memberID");
$this->newmodel->COURSE = $this->input->post("course");
$this->newmodel->CENTRE = $this->input->post("centre");
$this->newmodel->REGDATE = date('d/m/Y');
$this->newmodel->IMGNAME= $imgname;
$mydata = $this->newmodel->insertuserdata();
$data = array(
'name' => $this->newmodel->NAME,
'age' => $this->newmodel->AGE,
'place' => $this->newmodel->PLACE,
'address' => $this->newmodel->ADDRESS,
'phone' => $this->newmodel->PHONE,
'email' => $this->newmodel->MAIL,
'quali' => $this->newmodel->QUALI,
'occup' => $this->newmodel->OCCUP,
'milmaid' => $this->newmodel->MILMAID,
'course' => $this->newmodel->COURSE,
'centre' => $this->newmodel->CENTRE,
'regdate' => $this->newmodel->REGDATE,
'imgname' => $this->newmodel->IMGNAME,
);
$this->load->helper('url');
$this->load->view('users/admitcard',$data);
My Model codes are seem like this:
var $NAME = '';
var $AGE = 0;
var $PLACE = '';
var $ADDRESS = '';
var $PHONE = 0;
var $MAIL = '';
var $QUALI = '';
var $OCCUP = '';
var $MILMAID = '';
var $COURSE = '';
var $CENTRE = '';
var $REGDATE = '';
var $IMGNAME ='';
public function insertuserdata(){
$this->load->database();
$datas = array(
'Tname' => $this->NAME,
'Tage' => $this->AGE,
'Tplace' => $this->PLACE,
'TAddres' => $this->ADDRESS,
'Tph' => $this->PHONE,
'Tmail' => $this->MAIL,
'Tqualification' => $this->QUALI,
'Toccupation' => $this->OCCUP,
'TmilmaMemb' => $this->MILMAID,
'Tcourse' => $this->COURSE,
'Tcentre' => $this->CENTRE,
'regDate' => $this->REGDATE
);
$this->db->insert('tbl_trainers', $datas);
Try this code on your model
public function insertuserdata(){
$this->load->database();
$datas = array(
'Tname' => $this->input->post("name"),
'Tage' => $this->input->post("age"),
'Tplace' => $this->input->post("place"),
'TAddres' => $this->input->post("address"),
'Tph' => $this->input->post("phone"),
'Tmail' => $this->input->post("email"),
'Tqualification' => $this->input->post("qualification"),
'Toccupation' => $this->input->post("occupation"),
'TmilmaMemb' => $this->input->post("memberID"),
'Tcourse' => $this->input->post("course"),
'Tcentre' => $this->input->post("centre"),
'regDate' => date('d/m/Y')
);
$this->db->insert('tbl_trainers', $datas);
}
And simply call this model on your controller. Now your controller look like this-
public function yourMethod(){
$this->load->model('newmodel');
$this->newmodel->insertuserdata();
# And your rest code here...
}

REST CODEIGNITER multiple upload file

i'm try to build REST API use codeigniter plugin from https://github.com/chriskacerguis/codeigniter-restserver
i'm successfull built multiple upload with this, but i have a trouble when upload many file data.
when i'm select 3 file in my directory, my code work, but in upload path i just have 2 file.
here controller :
function upload_post()
{
$name_array = array();
$count = count($_FILES['userfile']['size']);
foreach($_FILES as $key=>$value)
{
for($s=0; $s<=$count-1; ) {
$_FILES['userfile']['name']=$value['name'][$s];
$_FILES['userfile']['type'] = $value['type'][$s];
$_FILES['userfile']['tmp_name'] = $value['tmp_name'][$s];
$_FILES['userfile']['error'] = $value['error'][$s];
$_FILES['userfile']['size'] = $value['size'][$s];
$config['upload_path'] = 'E:/tes/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '100000';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$this->load->library('upload', $config);
$this->upload->do_upload();
$data = $this->upload->data();
$name_array[] = $data['file_name'];
$s++;
}
}
$names= implode(',', $name_array);
/* $this->load->database();
$db_data = array('id'=> NULL,
'name'=> $names);
$this->db->insert('testtable',$db_data);
*/ print_r($names);
print_r($count);
}
I have made a helper function for me which upload the files and return a array with upload result.It takes a parameter upload directory where to save the files. Here is the my function
function upload_file($save_dir="images")//takes folder name where to save.default images folder
{
$CI = & get_instance();
$CI->load->library('upload');
$config=array();
$config['upload_path'] = FCPATH.$save_dir;
$config['allowed_types'] = 'gif|jpg|png';//only images.you can set more
$config['max_size'] = 1024*10;//10 mb you can increase more.Make sure your php.ini has congifured same or more value like this
$config['overwrite'] = false;//if file do not replace.create new file
$config['remove_spaces'] = true;//remove sapces from file
//you can set more config like height width for images
$uploaded_files=array();
foreach ($_FILES as $key => $value)
{
if(strlen($value['name'])>0)
{
$CI->upload->initialize($config);
if (!$CI->upload->do_upload($key))
{
$uploaded_files[$key]=array("status"=>false,"message"=>$value['name'].': '.$CI->upload->display_errors());
}
else
{
$uploaded_files[$key]=array("status"=>true,"info"=>$CI->upload->data());
}
}
}
return $uploaded_files;
}
Sample output
if you print out the function returns you will get the output like this
Array
(
[file_input_name1] => Array
(
[status] => 1//status will be true if uploaded
[info] => Array //if success it will return the file informattion
(
[file_name] => newfilename.jpg
[file_type] => image/jpeg
[file_path] => C:/Program Files (x86)/VertrigoServ/www/rnd/images/
[full_path] => C:/Program Files (x86)/VertrigoServ/www/rnd/images/newfilename.jpg
[raw_name] => newfilename
[orig_name] => newfilename.jpg
[client_name] => newfilename
[file_ext] => .jpg
[file_size] => 762.53
[is_image] => 1
[image_width] => 1024
[image_height] => 768
[image_type] => jpeg
[image_size_str] => width="1024" height="768"
)
)
[file_input_name_2] => Array
(
[status] =>//if invalid file status will be false with error message
[message] => desktop.ini: <p>The filetype you are attempting to upload is not allowed.</p>
)
)
Hope it may help you

Codeigniter 2.1 - fileupload You did not select a file to upload

Model function:
public function file_upload($folder, $allowed_type, $max_size = 0, $max_width = 0, $max_height = 0)
{
$folder = $this->path . $folder;
$files = array();
$count = 0;
foreach ($_FILES as $key => $value) :
$file_name = is_array($value['name']) ? $value['name'][$count] : $value['name'];
$file_name = $this->global_functions->char_replace($file_name, '_');
$count++;
$config = array(
'allowed_types' => $allowed_type,
'upload_path' => $folder,
'file_name' => $file_name,
'max_size' => $max_size,
'max_width' => $max_width,
'max_height' => $max_height,
'remove_spaces' => TRUE
);
$this->load->library('image_lib');
$this->image_lib->clear();
$this->load->library('upload');
$this->upload->initialize($config);
if (!$this->upload->do_upload($key)) :
$error = array('error' => $this->upload->display_errors());
var_dump($error);
return FALSE;
else :
$file = $this->upload->data();
$files[] = $file['file_name'];
endif;
endforeach;
if(empty($files)):
return FALSE;
else:
return implode(',', $files);
endif;
}
This function is working partially. Files are being uploaded to the selected folder, but I am getting this error: You did not select a file to upload. and getting FALSE as a result? What seems to be a problem? (form is using form_open_multipart)
Please make sure that you have this name of your file tag field:
$key='userfile' //which is name of input type field name
Are any of your file inputs empty when this happens? $_FILES will contain an array of "empty" data if there is no file specified for the input. For example, my file input name is one, and I submitted it without specifying a file:
Array
(
[one] => Array
(
[name] =>
[type] =>
[tmp_name] =>
[error] => 4
[size] => 0
)
)
You should check if the file data is empty before processing the upload. PHP's is_uploaded_file() is useful for this.

Codeigniter REST Upload Multiple Images

I'm absolutely stuck on this... checked all related stackoverflow posts and nothing has helped. Using Phil's REST Server / Client setup in Codeigniter and can insert normal entries but cannot upload multiple images, actually even a single image.
I can't really work out how to debug the REST part, it just returns nothing.
I have this array coming in from the view:
Array
(
[1] => Array
(
[name] => sideshows.jpg
[type] => image/jpeg
[tmp_name] => /Applications/MAMP/tmp/php/phppYycdA
[error] => 0
[size] => 967656
)
[2] => Array
(
[name] => the-beer-scale.jpg
[type] => image/jpeg
[tmp_name] => /Applications/MAMP/tmp/php/phpCsiunQ
[error] => 0
[size] => 742219
)
[3] => Array
(
[name] => the-little-lace.jpg
[type] => image/jpeg
[tmp_name] => /Applications/MAMP/tmp/php/phpXjT7WL
[error] => 0
[size] => 939963
)
[4] => Array
(
[name] => varrstoen-australia.jpg
[type] => image/jpeg
[tmp_name] => /Applications/MAMP/tmp/php/phpcHrJXe
[error] => 0
[size] => 2204400
)
)
I am using this helper method I found to sort out multiple file uploads:
function multifile_array()
{
if(count($_FILES) == 0)
return;
$files = array();
$all_files = $_FILES['files']['name'];
$i = 0;
foreach ($all_files as $filename) {
$files[++$i]['name'] = $filename;
$files[$i]['type'] = current($_FILES['files']['type']);
next($_FILES['files']['type']);
$files[$i]['tmp_name'] = current($_FILES['files']['tmp_name']);
next($_FILES['files']['tmp_name']);
$files[$i]['error'] = current($_FILES['files']['error']);
next($_FILES['files']['error']);
$files[$i]['size'] = current($_FILES['files']['size']);
next($_FILES['files']['size']);
}
$_FILES = $files;
}
This function is being called within the API controller:
public function my_file_upload_post() {
if( ! $this->post('submit')) {
$this->response(NULL, 400);
}
$data = $this->post('data');
multifile_array();
$foldername = './uploads/' . $this->post('property_id');
if(!file_exists($foldername) && !is_dir($foldername)) {
mkdir($foldername, 0750, true);
}
$config['upload_path'] = $foldername;
$config['allowed_types'] = 'gif|jpg|png|doc|docx|pdf|xlsx|xls|txt';
$config['max_size'] = '10240';
$this->load->library('upload', $config);
foreach ($data as $file => $file_data) {
$this->upload->do_upload($file);
//echo '<pre>';
//print_r($this->upload->data());
//echo '</pre>';
}
if ( ! $this->upload->do_upload() ) {
return $this->response(array('error' => strip_tags($this->upload->display_errors())), 404);
} else {
$upload = $this->upload->data();
return $this->response($upload, 200);
}
}
I am happy to share my code, I did manage to get multiple files uploading no worries, but just trying to set it up with the API so I can call it from an external website, internally or an iPhone. Help would be appreciated.
Cheers
Update:
Here is the code from the API Controller:
function upload_post() {
$foldername = './uploads/' . $this->post('property_id');
if(!file_exists($foldername) && !is_dir($foldername)) {
mkdir($foldername, 0750, true);
}
$config['upload_path'] = $foldername;
$config['allowed_types'] = 'gif|jpg|png|doc|docx|pdf|xlsx|xls|txt';
$config['max_size'] = '10240';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
//return $this->response(array('error' => strip_tags($this->upload->display_errors())), 404);
return $this->response(array('error' => var_export($this->post('file'), true)), 404);
}
else
{
$data = array('upload_data' => $this->upload->data());
return $this->response(array('error' => $data['upload_data']), 404);
}
return $this->response(array('success' => 'successfully uploaded' ), 200);
}
This works if you go directly to the API from the form, but you need to put in the username and password within the browser. If I run this via the controller then it can't find the images.
This is not exactly what you asked for, but this is what I used to solve this problem. A PHP/jQuery upload widget!
http://blueimp.github.com/jQuery-File-Upload/

Categories