Multiple upload images using codeigniter - php

Hi i have this file upload of images, and i want to do with a multiple images. Ive been searching in google and i found any no luck at all. I have this code <input type="file" name="photo[]" multiple="" /> and in my controller here
echo ("<pre>");
print_r($_FILES);
echo ("</pre>s");
$name_array = array();
$count = count($_FILES['photo']['size']);
$ctr = 0;
if ($_FILES){
$files = $_FILES['photo'];
foreach($_FILES['photo']['name'] as $key=>$value){
$_FILES['photo']['name']= $files['name'][$ctr];
$_FILES['photo']['type'] = $files['type'][$ctr];
$_FILES['photo']['tmp_name'] = $files['tmp_name'][$ctr];
$_FILES['photo']['error'] = $files['error'][$ctr];
$_FILES['photo']['size'] = $files['size'][$ctr];
echo ("<pre> NEW >>> " . $ctr);
print_r($_FILES);
echo ("</pre>");
$ctr++;
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '2048';
//$config['max_width'] = '1024';
//$config['max_height'] = '768';
$this->load->library('upload', $config);
$this->upload->do_upload();
$data = $this->upload->data();
print_r($data);
$name_array[] = $data['file_name'];
$names= implode(',', $name_array);
/* $this->load->database();
$db_data = array('id'=> NULL,
'name'=> $names);
$this->db->insert('testtable',$db_data);
*/ print_r($names);
}
}
my action <?php echo form_open_multipart('post/add') ?>
and what ive got the error is this way
A PHP Error was encountered
Severity: Warning
Message: is_uploaded_file() expects parameter 1 to be string, array given
Filename: libraries/Upload.php
Line Number: 161
You did not select a file to upload.
Can someone help me figured this thing out? on how multiple uploads will do in codeigniter?? Any help is muchly appreciated. Thanks

controller:
class Imageupload extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->helper(array('form', 'url'));
}
function index()
{
$this->load->view('imageupload_view', array('error' => ' ' ));
}
function doupload() {
$name_array = array();
$count = count($_FILES['userfile']['size']);
foreach($_FILES as $key=>$value)
for($s=0; $s<=$count-1; $s++) {
$_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'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '100';
$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'];
}
$names= implode(',', $name_array);
/* $this->load->database();
$db_data = array('id'=> NULL,
'name'=> $names);
$this->db->insert('testtable',$db_data);
*/ print_r($names);
}
}
view:
<html>
<head>
<title>Upload Form</title>
</head>
<body>
<?php echo form_open_multipart('imageupload/doupload');?>
<input name="userfile[]" id="userfile" type="file" multiple="" />
<input type="submit" value="upload" />
<?php echo form_close() ?>
</body>
</html>

Try this:
$this->load->library('upload');
$files = $_FILES;
$cpt = count($_FILES['photo']['name']);
for($i=0; $i<$cpt; $i++)
{
$_FILES['photo']['name']= $files['photo']['name'][$i];
$_FILES['photo']['type']= $files['photo']['type'][$i];
$_FILES['photo']['tmp_name']= $files['photo']['tmp_name'][$i];
$_FILES['photo']['error']= $files['photo']['error'][$i];
$_FILES['photo']['size']= $files['photo']['size'][$i];
$config['upload_path'] = './uploads/';
....
....
$this->upload->initialize($config);
$this->upload->do_upload();
}

Related

Upload pictures and data create dynamically codeigniter

I need to upload pictures and data create dynamically html and jQuery I use codeigneter framework and send the the all data to mysql.
This is code controller
public function Addtest() {
$this->load->library('upload');
$u= $this->session->userdata('id_user');
$files = $_FILES;
$cpt = count($_FILES['sliderimg']['name']);
$inputAll= $this->input->post();
$this->load->model('AddData');
for($i=0; $i < count($inputAll['artilce']); $i++) {
$_FILES['sliderimg']['name']= $files['sliderimg']['name'][$i];
$_FILES['sliderimg']['type']= $files['sliderimg']['type'][$i];
// $_FILES['sliderimg']['tmp_name']= $files['sliderimg']['tmp_name'][$i];
$this->upload->initialize($this->set_upload_options());
$this->upload->do_upload();
var_dump($_FILES);
$data= array(
'id_user'=>$u,
'description2'=>$inputAll['description2'][$i],
'description1'=>$inputAll['description1'][$i],
'art'=>$inputAll['artilce'][$i],
$_FILES['sliderimg']['name']= $files['sliderimg']['name'][$i],
$image_name =>$_FILES['sliderimg']['name'][$i],
);
if( $this->AddData->Add_data($data)) {
echo 'false';
} else {
echo 'true';
}
and this the model code
public function Add_data($artt) {
extract($artt);
$data = array(
'Art'=>$art,
'des1'=>$description1,
'desc2'=>$description2,
'picture'=>$image_name,
'id_foreign'=>$id_user,
);
$this->db->insert('table',$data);
}
and the this the error output while I try to upload 2 pictures and data
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: image_name
and this is the set_upload_options() function
private function set_upload_options()
{
$config = array();
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['max_size'] = '2048000';
$config['max_width'] = '20000';
$config['max_height'] = '17680';
$config['overwrite'] = FALSE;
return $config;
}
and the do_uplaod:
public function do_upload() {
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['max_size'] = '2048000';
$config['max_width'] = '2024';
$config['max_height'] = '1068';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
return "false";
}
else
{
return "true";
}
}

how to upload multiple images and to show related images using codeigniter

i want to upload multiple images and display related images but iam getting an error you didnt select any file to upload
my view page is this
<div class="form-group col-md-12">
<label class="form-group col-md-3" for="exampleInputEmail1">Image</label>
<div class="form-group col-md-6">
<input type="file" class="" id="image" name="image[]">
</div>
</div>
my controler looks like this...
public function add_images()
{
$data['active_mn']='add_images';
if($_POST)
{
$this->form_validation->set_rules('title','title','required');
$this->form_validation->set_rules('parentname','parent category','required');
$this->form_validation->set_rules('subname','sub category','required');
$this->form_validation->set_rules('code','code','required');
$this->form_validation->set_rules('description','Description','required');
$this->form_validation->set_rules('size','Size','required');
if($this->form_validation->run()==true)
{
if($this->do_upload())
{
$stat=$this->roxmodel->add_images($this->upload->file_name);
if($stat)
{
$data=array();
$colors=array_filter($this->session->userdata('colors'));
/*creating a multidiemensional array to batch insert*/
foreach ($colors as $color)
{
$new_array=array('product_id'=>$stat,'color'=>$color);
array_push($data, $new_array);
}
$product=$this->roxmodel->add_product_color($data);
$this->session->unset_userdata('colors');
$this->session->set_flashdata('message', 'Gallery added Successfully.');
redirect('admin_control/view_images');
}
else
{
$this->session->set_flashdata('message', 'Insertion Failed.');
redirect('admin_control/add_images');
}
//redirect('admin_control/view_images');
}
}
}
$data['parent']=$this->roxmodel->get_parentcategory();
$this->load->view('add_images',$data);
}
my uploaded path looks like this..
function image_upload()
{
$name_array=array();
$count = count($_FILES['image']['size']);
foreach($_FILES as $key => $value)
{
for ($s = 0; $s < $count; $s++)
{
$config['upload_path'] = './images/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '5000';
$config['max_width'] = '4000';
$config['max_height'] = '6500';
$config['file_name'] ='img'.time();
$this->load->library('upload', $config);
if(! $this->upload->do_upload("image"))
{
$this->session->set_flashdata('message',$this->upload->display_errors());
return false;
}
else
{
$config['image_library'] = 'gd2';
$config['source_image'] = './images/'.$this->upload->file_name;
$config['create_thumb'] = TRUE;
$config['maintain_ratio'] = TRUE;
$config['width'] = 540;
$config['height'] = 660;
$config['new_image'] = './images/thumb/';
$this->load->library('image_lib', $config);
if(! $this->image_lib->resize())
{
$this->session->set_flashdata('message',$this->image_lib->display_errors());
return false;
}
else
{
return true;
}
}
}
}
}
Try like this to upload multiple images .. and please add enctype='multipart/form-data' in your form
$name_array=array();
$count = count($_FILES['image']['size']);
foreach($_FILES as $key => $value)
{
for ($s = 0; $s < $count; $s++)
{
$_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'] = "uploads/item_images/itemimage/original/";//your imagepath here
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '8000';
$config['max_width'] = '10240';
$config['max_height'] = '7680';
$this->load->library('upload', $config);
if ($this->upload->do_upload("image"))
{
$data = $this->upload->data();
if ($this->image_moo->errors)
{
print $this->upload->display_errors();
}
else
{
$name_array[] = $data['file_name'];
} } }
By default codeIgniter doesn't support multi-file upload. So you can use this library
CodeIgniter Multiple Upload Library

Upload only Two Image using two input field Using CodeIgniter

Controller
public function insertDepartmentImage()
{
$this->load->model('Gallery_Model/Gallery_Model');
$config['upload_path'] = './uploads/galleryImg';
$config['allowed_types'] = 'png|jpg|gif|jpeg';
$config['max_size'] = '10000000';
$config['file_name']='smallImage';
$config['file_name1']='bigImage';
$config['overwrite']=false;
$this->load->library('upload', $config);
if (!is_dir('uploads'))
{
mkdir('./uploads', 0777, true);
}
$dir_exist = true;
if (!is_dir('uploads/' . $album))
{
mkdir('./uploads/' . $album, 0777, true);
$dir_exist = false; // dir not exist
}
else{ }
if (!$this->upload->do_upload('filename'))
{
$this->load->model('Gallery_Model/Gallery_Model');
$upload_error = array('error' => $this->upload->display_errors());
$this->load->view('/admin/Gallery/vwGallery',$upload_error);
}
else
{
$upload_data = $this->upload->data();
$data['success_msg'] = '<div class="alert alert-success text-center">Your file <strong>' . $upload_data['file_name'] . '</strong> was successfully uploaded!</div>';
$this->load->model('Gallery_Model/Gallery_Model');
$file_name = $upload_data['file_name'];
$file_name1 = $upload_data['file_name1'];
$deptId = $this->input->post('deptId');
$deptDetails = $this->input->post('deptDetails');
$deptDetails1 = $this->input->post('deptDetails1');
$this->Gallery_Model->insertDepartmentImage($deptId,$file_name,$file_name1,$deptDetails,$deptDetails1);
}
}
It work fine but uploading only one filename into database. I have to upload one more image into database. But its not working.For Uploading Another image what to do for this.
In my view I have given two input field <input id="file-0" name="filename" class="file" type="file" multiple="true" />
<input id="file-0" name="filename1" class="file" type="file" multiple="true" />
Thank you guys. But I will just changing code into Controller and It's worked for me.
public function insertDepartmentImage()
{
$m = $_FILES['filename']['name'];
$n = $_FILES['filename1']['name'];
if ($m !== "")
{
$config['upload_path'] = './uploads/galleryImg';
$config['log_threshold'] = 1;
$config['allowed_types'] = 'jpg|png|jpeg|gif';
$config['max_size'] = '100000'; // 0 = no file size limit
$config['file_name']='smallImage';
$config['overwrite'] = false;
$this->load->library('upload', $config);
$this->upload->do_upload('filename');
$upload_data = $this->upload->data();
$file_name = $upload_data['file_name'];
}
if ($n !== "")
{
$config['file_name']='bigImage';
$config['upload_path'] = './uploads/galleryImg';
$config['allowed_types'] = 'jpg|png|jpeg|gif';
$config['max_size'] = '100000'; // 0 = no file size limit
$config['overwrite'] = false;
$this->load->library('upload', $config);
$this->upload->do_upload('filename1');
$upload_data = $this->upload->data();
$file_name1 = $upload_data['file_name'];
}
$deptId = $this->input->post('deptId');
$deptDetails = $this->input->post('deptDetails');
$deptDetails1 = $this->input->post('deptDetails1');
$this->Gallery_Model->insertDepartmentImage($deptId,$file_name,$file_name1,$deptDetails,$deptDetails1);
}/* closed insertDepartmentImage*/
View
<input id="file-0" name="filename" class="file" type="file" multiple="true" />
<input id="file-0" name="filename1" class="file" type="file" multiple="true" />
By default codeIgniter doesn't support multi-file upload. So you can use this library CodeIgniter Multiple Upload Library
https://github.com/anuragrath/CodeIgniter-Multiple-File-Upload
Thank you guys... I solve my problem now...
Here are my code, hope it can help
public function dashboard_templatedefault(){
$upload1 = $_FILES['upload1']['name'];
$upload2 = $_FILES['upload2']['name'];
$upload3 = $_FILES['upload3']['name'];
$upload4 = $_FILES['upload4']['name'];
$upload5 = $_FILES['upload5']['name'];
$upload6 = $_FILES['upload6']['name'];
$upload7 = $_FILES['upload7']['name'];
$upload8 = $_FILES['upload8']['name'];
if($upload1 !== ""){
$config['upload_path'] = './upload/';
$config['log_threshold'] = 1;
$config['allowed_types'] = 'jpg|png|jpeg|gif';
$config['max_size'] = '0'; // 0 = no file size limit
$config['file_name']='upload1';
$config['overwrite'] = false;
$this->load->library('upload', $config);
$this->upload->do_upload('upload1');
$upload_data = $this->upload->data();
$file_name = $upload_data['file_name'];
}
if($upload2 !== ""){
$config['file_name']='upload2';
$config['upload_path'] = './upload/';
$config['allowed_types'] = 'jpg|png|jpeg|gif';
$config['max_size'] = '0'; // 0 = no file size limit
$config['overwrite'] = false;
$this->load->library('upload', $config);
$this->upload->do_upload('upload2');
$upload_data = $this->upload->data();
$file_name1 = $upload_data['file_name'];
}
if($upload3 !== ""){
$config['file_name']='upload3';
$config['upload_path'] ='./upload/';
$config['allowed_types'] ='jpg|png|jpeg|gif';
$config['max_size'] = '0';
$config['overwrite'] = false;
$this->load->library('upload',$config);
$this->upload->do_upload('upload3');
$upload_data = $this->upload->data();
$file_name2 = $upload_data['file_name'];
}
if($upload4 !== ""){
$config['file_name'] = 'upload4';
$config['upload_path'] ='./upload/';
$config['allowed_types'] = 'jpg|png|jpeg|gif';
$config['max_size'] ='0';
$config['overwrite'] = false;
$this->load->library('upload',$config);
$this->upload->do_upload('upload4');
$upload_data = $this->upload->data();
$file_name3 = $upload_data['file_name'];
}
if($upload5 !== ""){
$config['file_name'] = 'upload5';
$config['upload_path'] ='./upload/';
$config['allowed_types'] = 'jpg|png|jpeg|gif';
$config['max_size'] ='0';
$config['overwrite'] = false;
$this->load->library('upload',$config);
$this->upload->do_upload('upload5');
$upload_data = $this->upload->data();
$file_name4 = $upload_data['file_name'];
}
if($upload6 !== ""){
$config['file_name'] = 'upload6';
$config['upload_path'] ='./upload/';
$config['allowed_types'] = 'jpg|png|jpeg|gif';
$config['max_size'] ='0';
$config['overwrite'] = false;
$this->load->library('upload',$config);
$this->upload->do_upload('upload6');
$upload_data = $this->upload->data();
$file_name5 = $upload_data['file_name'];
}
if($upload7 !== ""){
$config['file_name'] = 'upload7';
$config['upload_path'] ='./upload/';
$config['allowed_types'] = 'jpg|png|jpeg|gif';
$config['max_size'] ='0';
$config['overwrite'] = false;
$this->load->library('upload',$config);
$this->upload->do_upload('upload7');
$upload_data = $this->upload->data();
$file_name6 = $upload_data['file_name'];
}
if($upload8 !== ""){
$config['file_name'] = 'upload8';
$config['upload_path'] ='./upload/';
$config['allowed_types'] = 'jpg|png|jpeg|gif';
$config['max_size'] ='0';
$config['overwrite'] = false;
$this->load->library('upload',$config);
$this->upload->do_upload('upload8');
$upload_data = $this->upload->data();
$file_name7 = $upload_data['file_name'];
}
$this->form_validation->set_rules('name','','xss_clean');
$this->form_validation->set_rules('occasion','','xss_clean');
$this->form_validation->set_rules('party_date','','xss_clean');
$this->form_validation->set_rules('location','','xss_clean');
$this->form_validation->set_rules('upload1','','xss_clean');
$this->form_validation->set_rules('upload2','','xss_clean');
$this->form_validation->set_rules('upload3','','xss_clean');
$this->form_validation->set_rules('upload4','','xss_clean');
$this->form_validation->set_rules('upload5','','xss_clean');
$this->form_validation->set_rules('upload6','','xss_clean');
$this->form_validation->set_rules('upload7','','xss_clean');
$this->form_validation->set_rules('upload8','','xss_clean');
$this->form_validation->run();
$template_name = $this->input->post('template_name');
$name = $this->input->post('name');
$occasion = $this->input->post('occasion');
$party_date = $this->input->post('party_date');
$location = $this->input->post('location');
$created = date('h:m:s a m/d/y');
$profile_id = $this->input->post('profile_id');
$this->admin_model->dashboard_templatedefault($template_name,$name,$occasion,$party_date,$location,$created,$profile_id,$upload1,$upload2,$upload3,$upload4,$upload5,$upload6,$upload7,$upload8);
}
You code is seems too long try this one
public function insertDepartmentImage()
{
$upload1 = $_FILES['upload1']['name'];
$upload2 = $_FILES['upload2']['name'];
$config = array(
'upload_path' => './uploads/galleryImg/',
'log_threshold' => 1,
'allowed_types' => 'jpg|png|jpeg|gif',
'max_size' => '0',
'overwrite' => false
);
for($i = 1; $i<=2; $i++){
if(!empty('$upload'.$i)){
$config['file_name']='upload'.$i;
$this->load->library('upload', $config);
$this->upload->do_upload('upload'.$i);
$upload_data = $this->upload->data();
$file_name = $upload_data['file_name'];
}
}
$deptId = $this->input->post('deptId');
$deptDetails = $this->input->post('deptDetails');
$deptDetails1 = $this->input->post('deptDetails1');
$this->Gallery_Model->insertDepartmentImage($deptId,$file_name,$file_name1,$deptDetails,$deptDetails1);
}

multiple image upload in single input [duplicate]

I've been searching and struggling for 3 days now to make this works but I just can't.
What I want to do is use a Multiple file input form and then upload them. I can't just use a fixed number of file to upload. I tried many many solutions on StackOverflow but I wasn't able to find a working one.
Here's my Upload controller
<?php
class Upload extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->helper(array('form', 'url','html'));
}
function index()
{
$this->load->view('pages/uploadform', array('error' => ' ' ));
}
function do_upload()
{
$config['upload_path'] = './Images/';
$config['allowed_types'] = 'gif|jpg|png';
$this->load->library('upload');
foreach($_FILES['userfile'] as $key => $value)
{
if( ! empty($key['name']))
{
$this->upload->initialize($config);
if ( ! $this->upload->do_upload($key))
{
$error['error'] = $this->upload->display_errors();
$this->load->view('pages/uploadform', $error);
}
else
{
$data[$key] = array('upload_data' => $this->upload->data());
$this->load->view('pages/uploadsuccess', $data[$key]);
}
}
}
}
}
?>
My upload form is This.
<html>
<head>
<title>Upload Form</title>
</head>
<body>
<?php echo $error;?>
<?php echo form_open_multipart('upload/do_upload');?>
<input type="file" multiple name="userfile[]" size="20" />
<br /><br />
<input type="submit" value="upload" />
</form>
</body>
</html>
I just keep having this error :
You did not select a file to upload.
Here's the array of the example:
Array ( [userfile] => Array ( [name] => Array ( [0] => youtube.png [1] => zergling.jpg ) [type] => Array ( [0] => image/png [1] => image/jpeg ) [tmp_name] => Array ( [0] => E:\wamp\tmp\php7AC2.tmp [1] => E:\wamp\tmp\php7AC3.tmp ) [error] => Array ( [0] => 0 [1] => 0 ) [size] => Array ( [0] => 35266 [1] => 186448 ) ) )
I have this like 5 times in a row if I select 2 files.
I also use the standard Upload library.
I finally managed to make it work with your help!
Here's my code:
function do_upload()
{
$this->load->library('upload');
$files = $_FILES;
$cpt = count($_FILES['userfile']['name']);
for($i=0; $i<$cpt; $i++)
{
$_FILES['userfile']['name']= $files['userfile']['name'][$i];
$_FILES['userfile']['type']= $files['userfile']['type'][$i];
$_FILES['userfile']['tmp_name']= $files['userfile']['tmp_name'][$i];
$_FILES['userfile']['error']= $files['userfile']['error'][$i];
$_FILES['userfile']['size']= $files['userfile']['size'][$i];
$this->upload->initialize($this->set_upload_options());
$this->upload->do_upload();
}
}
private function set_upload_options()
{
//upload an image options
$config = array();
$config['upload_path'] = './Images/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '0';
$config['overwrite'] = FALSE;
return $config;
}
Thank you guys!
You should use this library for multi upload in CI https://github.com/stvnthomas/CodeIgniter-Multi-Upload
Installation Simply copy the MY_Upload.php file to your applications library directory.
Use: function test_up in controller
public function test_up(){
if($this->input->post('submit')){
$path = './public/test_upload/';
$this->load->library('upload');
$this->upload->initialize(array(
"upload_path"=>$path,
"allowed_types"=>"*"
));
if($this->upload->do_multi_upload("myfile")){
echo '<pre>';
print_r($this->upload->get_multi_upload_data());
echo '</pre>';
}
}else{
$this->load->view('test/upload_view');
}
}
upload_view.php in applications/view/test folder
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="myfile[]" id="myfile" multiple>
<input type="submit" name="submit" id="submit" value="submit"/>
Try this code.
It's working fine for me
You must initialize each time the library
function do_upload()
{
foreach ($_FILES as $index => $value)
{
if ($value['name'] != '')
{
$this->load->library('upload');
$this->upload->initialize($this->set_upload_options());
//upload the image
if ( ! $this->upload->do_upload($index))
{
$error['upload_error'] = $this->upload->display_errors("<span class='error'>", "</span>");
//load the view and the layout
$this->load->view('pages/uploadform', $error);
return FALSE;
}
else
{
$data[$key] = array('upload_data' => $this->upload->data());
$this->load->view('pages/uploadsuccess', $data[$key]);
}
}
}
}
private function set_upload_options()
{
//upload an image options
$config = array();
$config['upload_path'] = 'your upload path';
$config['allowed_types'] = 'gif|jpg|png';
return $config;
}
Further edit
I have found the way you must upload your files with one unique input box
CodeIgniter doesn't support multiple files. Using the do_upload() in a foreach won't be different than using it outside.
You will need to deal with it without the help of CodeIgniter. Here's an example https://github.com/woxxy/FoOlSlide/blob/master/application/controllers/admin/series.php#L331-370
https://stackoverflow.com/a/9846065/1171049
This is that said you in the commments :)
another bit of code here:
refer: https://github.com/stvnthomas/CodeIgniter-Multi-Upload
As Carlos Rincones suggested; don't be affraid of playing with superglobals.
$files = $_FILES;
for($i=0; $i<count($files['userfile']['name']); $i++)
{
$_FILES = array();
foreach( $files['userfile'] as $k=>$v )
{
$_FILES['userfile'][$k] = $v[$i];
}
$this->upload->do_upload('userfile')
}
All Posted files will be come in $_FILES variable, for use codeigniter upload library we need to give field_name that we are using in for upload (by default it will be 'userfile'), so we get all posted file and create another files array that create our own name for each files, and give this name to codeigniter library do_upload function.
if(!empty($_FILES)){
$j = 1;
foreach($_FILES as $filekey=>$fileattachments){
foreach($fileattachments as $key=>$val){
if(is_array($val)){
$i = 1;
foreach($val as $v){
$field_name = "multiple_".$filekey."_".$i;
$_FILES[$field_name][$key] = $v;
$i++;
}
}else{
$field_name = "single_".$filekey."_".$j;
$_FILES[$field_name] = $fileattachments;
$j++;
break;
}
}
// Unset the useless one
unset($_FILES[$filekey]);
}
foreach($_FILES as $field_name => $file){
if(isset($file['error']) && $file['error']==0){
$config['upload_path'] = [upload_path];
$config['allowed_types'] = [allowed_types];
$config['max_size'] = 100;
$config['max_width'] = 1024;
$config['max_height'] = 768;
$this->load->library('upload', $config);
$this->upload->initialize($config);
if ( ! $this->upload->do_upload($field_name)){
$error = array('error' => $this->upload->display_errors());
echo "Error Message : ". $error['error'];
}else{
$data = $this->upload->data();
echo "Uploaded FileName : ".$data['file_name'];
// Code for insert into database
}
}
}
}
public function imageupload()
{
$count = count($_FILES['userfile']['size']);
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png|bmp';
$config['max_size'] = '0';
$config['max_width'] = '0';
$config['max_height'] = '0';
$config['image_library'] = 'gd2';
$config['create_thumb'] = TRUE;
$config['maintain_ratio'] = FALSE;
$config['width'] = 50;
$config['height'] = 50;
foreach($_FILES as $key=>$value)
{
for($s=0; $s<=$count-1; $s++)
{
$_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];
$this->load->library('upload', $config);
if ($this->upload->do_upload('userfile'))
{
$data['userfile'][$i] = $this->upload->data();
$full_path = $data['userfile']['full_path'];
$config['source_image'] = $full_path;
$config['new_image'] = './uploads/resiezedImage';
$this->load->library('image_lib', $config);
$this->image_lib->resize();
$this->image_lib->clear();
}
else
{
$data['upload_errors'][$i] = $this->upload->display_errors();
}
}
}
}
I have used below code in my custom library
call that from my controller like below,
function __construct() {<br />
parent::__construct();<br />
$this->load->library('CommonMethods');<br />
}<br />
$config = array();<br />
$config['upload_path'] = 'assets/upload/images/';<br />
$config['allowed_types'] = 'gif|jpg|png|jpeg';<br />
$config['max_width'] = 150;<br />
$config['max_height'] = 150;<br />
$config['encrypt_name'] = TRUE;<br />
$config['overwrite'] = FALSE;<br />
// upload multiplefiles<br />
$fileUploadResponse = $this->commonmethods->do_upload_multiple_files('profile_picture', $config);
/**
* do_upload_multiple_files - Multiple Methods
* #param type $fieldName
* #param type $options
* #return type
*/
public function do_upload_multiple_files($fieldName, $options) {
$response = array();
$files = $_FILES;
$cpt = count($_FILES[$fieldName]['name']);
for($i=0; $i<$cpt; $i++)
{
$_FILES[$fieldName]['name']= $files[$fieldName]['name'][$i];
$_FILES[$fieldName]['type']= $files[$fieldName]['type'][$i];
$_FILES[$fieldName]['tmp_name']= $files[$fieldName]['tmp_name'][$i];
$_FILES[$fieldName]['error']= $files[$fieldName]['error'][$i];
$_FILES[$fieldName]['size']= $files[$fieldName]['size'][$i];
$this->CI->load->library('upload');
$this->CI->upload->initialize($options);
//upload the image
if (!$this->CI->upload->do_upload($fieldName)) {
$response['erros'][] = $this->CI->upload->display_errors();
} else {
$response['result'][] = $this->CI->upload->data();
}
}
return $response;
}
<form method="post" action="<?php echo base_url('submit'); ?>" enctype="multipart/form-data">
<input type="file" name="userfile[]" id="userfile" multiple="" accept="image/*">
</form>
MODEL : FilesUpload
class FilesUpload extends CI_Model {
public function setFiles()
{
$name_array = array();
$count = count($_FILES['userfile']['size']);
foreach ($_FILES as $key => $value)
for ($s = 0; $s <= $count - 1; $s++) {
$_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'] = 'assets/product/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '10000000';
$config['max_width'] = '51024';
$config['max_height'] = '5768';
$this->load->library('upload', $config);
if (!$this->upload->do_upload()) {
$data_error = array('msg' => $this->upload->display_errors());
var_dump($data_error);
} else {
$data = $this->upload->data();
}
$name_array[] = $data['file_name'];
}
$names = implode(',', $name_array);
return $names;
}
}
CONTROLER submit
class Submit extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->helper(array('html', 'url'));
}
public function index()
{
$this->load->model('FilesUpload');
$data = $this->FilesUpload->setFiles();
echo '<pre>';
print_r($data);
}
}
// Change $_FILES to new vars and loop them
foreach($_FILES['files'] as $key=>$val)
{
$i = 1;
foreach($val as $v)
{
$field_name = "file_".$i;
$_FILES[$field_name][$key] = $v;
$i++;
}
}
// Unset the useless one ;)
unset($_FILES['files']);
// Put each errors and upload data to an array
$error = array();
$success = array();
// main action to upload each file
foreach($_FILES as $field_name => $file)
{
if ( ! $this->upload->do_upload($field_name))
{
echo ' failed ';
}else{
echo ' success ';
}
}
function imageUpload(){
if ($this->input->post('submitImg') && !empty($_FILES['files']['name'])) {
$filesCount = count($_FILES['files']['name']);
$userID = $this->session->userdata('userID');
$this->load->library('upload');
$config['upload_path'] = './userdp/';
$config['allowed_types'] = 'jpg|png|jpeg';
$config['max_size'] = '9184928';
$config['max_width'] = '5000';
$config['max_height'] = '5000';
$files = $_FILES;
$cpt = count($_FILES['files']['name']);
for($i = 0 ; $i < $cpt ; $i++){
$_FILES['files']['name']= $files['files']['name'][$i];
$_FILES['files']['type']= $files['files']['type'][$i];
$_FILES['files']['tmp_name']= $files['files']['tmp_name'][$i];
$_FILES['files']['error']= $files['files']['error'][$i];
$_FILES['files']['size']= $files['files']['size'][$i];
$imageName = 'image_'.$userID.'_'.rand().'.png';
$config['file_name'] = $imageName;
$this->upload->initialize($config);
if($this->upload->do_upload('files')){
$fileData = $this->upload->data(); //it return
$uploadData[$i]['picturePath'] = $fileData['file_name'];
}
}
if (!empty($uploadData)) {
$imgInsert = $this->insert_model->insertImg($uploadData);
$statusMsg = $imgInsert?'Files uploaded successfully.':'Some problem occurred, please try again.';
$this->session->set_flashdata('statusMsg',$statusMsg);
redirect('home/user_dash');
}
}
else{
redirect('home/user_dash');
}
}
There is no predefined method available in codeigniter to upload multiple file at one time but you can send file in array and upload them one by one
here is refer: Here is best option to upload multiple file in codeigniter 3.0.1 with preview https://codeaskbuzz.com/how-to-upload-multiple-file-in-codeigniter-framework/
SO what I change is I load upload library each time
$config = array();
$config['upload_path'] = $filePath;
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '0';
$config['overwrite'] = FALSE;
$files = $_FILES;
$count = count($_FILES['nameUpload']['name']);
for($i=0; $i<$count; $i++)
{
$this->load->library('upload', $config);
$_FILES['nameUpload']['name']= $files['nameUpload']['name'][$i];
$_FILES['nameUpload']['type']= $files['nameUpload']['type'][$i];
$_FILES['nameUpload']['tmp_name']= $files['nameUpload']['tmp_name'][$i];
$_FILES['nameUpload']['error']= $files['nameUpload']['error'][$i];
$_FILES['nameUpload']['size']= $files['nameUpload']['size'][$i];
$this->upload->do_upload('nameUpload');
}
And it work for me.
For CodeIgniter 3
<form action="<?php echo base_url('index.php/TestingController/insertdata') ?>" method="POST"
enctype="multipart/form-data">
<div class="form-group">
<label for="">title</label>
<input type="text" name="title" id="title" class="form-control">
</div>
<div class="form-group">
<label for="">File</label>
<input type="file" name="files" id="files" class="form-control">
</div>
<input type="submit" value="Submit" class="btn btn-primary">
</form>
public function insertdatanew()
{
$this->load->library('upload');
$files = $_FILES;
$cpt = count($_FILES['filesdua']['name']);
for ($i = 0; $i < $cpt; $i++) {
$_FILES['filesdua']['name'] = $files['filesdua']['name'][$i];
$_FILES['filesdua']['type'] = $files['filesdua']['type'][$i];
$_FILES['filesdua']['tmp_name'] = $files['filesdua']['tmp_name'][$i];
$_FILES['filesdua']['error'] = $files['filesdua']['error'][$i];
$_FILES['filesdua']['size'] = $files['filesdua']['size'][$i];
// fungsi uploud
$config['upload_path'] = './uploads/testing/';
$config['allowed_types'] = '*';
$config['max_size'] = 0;
$config['max_width'] = 0;
$config['max_height'] = 0;
$this->load->library('upload', $config);
$this->upload->initialize($config);
if (!$this->upload->do_upload('filesdua')) {
$error = array('error' => $this->upload->display_errors());
var_dump($error);
// $this->load->view('welcome_message', $error);
} else {
// menambil nilai value yang di upload
$data = array('upload_data' => $this->upload->data());
$nilai = $data['upload_data'];
$filename = $nilai['file_name'];
var_dump($filename);
// $this->load->view('upload_success', $data);
}
}
// var_dump($cpt);
}
I recently work on it. Try this function:
/**
* #return array an array of your files uploaded.
*/
private function _upload_files($field='userfile'){
$files = array();
foreach( $_FILES[$field] as $key => $all )
foreach( $all as $i => $val )
$files[$i][$key] = $val;
$files_uploaded = array();
for ($i=0; $i < count($files); $i++) {
$_FILES[$field] = $files[$i];
if ($this->upload->do_upload($field))
$files_uploaded[$i] = $this->upload->data($files);
else
$files_uploaded[$i] = null;
}
return $files_uploaded;
}
in your case:
<input type="file" multiple name="images[]" size="20" />
or
<input type="file" name="images[]">
<input type="file" name="images[]">
<input type="file" name="images[]">
in the controller:
public function do_upload(){
$config['upload_path'] = './Images/';
$config['allowed_types'] = 'gif|jpg|png';
//...
$this->load->library('upload',$config);
if ($_FILES['images']) {
$images= $this->_upload_files('images');
print_r($images);
}
}
Some basic reference from PHP manual: PHP file upload
Save, then redefine the variable $_FILES to whatever you need.
maybe not the best solution, but this worked for me.
function do_upload()
{
$this->load->library('upload');
$this->upload->initialize($this->set_upload_options());
$quantFiles = count($_FILES['userfile']['name']);
for($i = 0; $i < $quantFiles ; $i++)
{
$arquivo[$i] = array
(
'userfile' => array
(
'name' => $_FILES['userfile']['name'][$i],
'type' => $_FILES['userfile']['type'][$i],
'tmp_name' => $_FILES['userfile']['tmp_name'][$i],
'error' => $_FILES['userfile']['error'][$i],
'size' => $_FILES['userfile']['size'][$i]
)
);
}
for($i = 0; $i < $quantFiles ; $i++)
{
$_FILES = '';
$_FILES = $arquivo[$i];
if ( ! $this->upload->do_upload())
{
$error[$i] = array('error' => $this->upload->display_errors());
return FALSE;
}
else
{
$data[$i] = array('upload_data' => $this->upload->data());
var_dump($this->upload->data());
}
}
if(isset($error))
{
$this->index($error);
}
else
{
$this->index($data);
}
}
the separate function to establish the config..
private function set_upload_options()
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'xml|pdf';
$config['max_size'] = '10000';
return $config;
}

How can i insert the document type(name) and its respective image in database with every file upload in codeigniter

What exactly i need to do is: User can select the Document Type (like, passport, driving licence, voter Id etc.) from the drop down and the its respective image he wants to upload. Suppose he is to upload 4 documents then he should be able to select the document type for each upload from the drop-down next to the "file" input type :
This is the code i tried so far, but it is inserting Nothing in the table, though it is working fine with one drop-down and multiple file upload
In my controller:
$this->customer_model->upload_doc();
redirect('/customer/index', 'location', 301);
In Model:
public function upload_doc()
{
if(isset($_FILES['userfile']))
{
$name_array = array();
$count = count($_FILES['userfile']['size']);
foreach($_FILES as $key=>$value)
for($s=0; $s<=$count-1; $s++)
{
$_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'] = './assets/document/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '';
$config['max_width'] = '';
$config['max_height'] = '';
$this->load->library('upload', $config);
$this->upload->do_upload();
$data = $this->upload->data();
$name_array[] = $data['file_name'];
}
//$names= implode(',', $name_array);
foreach($name_array as $name)
{
$db_data = array(
'documentType' => $this->input->post('idproof'),
'image' => $name,
);
$this->db->insert('document',$db_data);
}
//print_r($db_data);
//die();
//die();
//print_r($names);
}
}
In View:
Id Proof<?php echo form_dropdown('idProof1', $document,'', 'class= "form-control"'); ?><input type="file" name="userfile[]" id="userfile" size="20" />
<?php echo form_dropdown('idProof2', $document,'', 'class= "form-control"'); ?> <input type="file" name="userfile[]" id="userfile" size="20" />
<?php echo form_dropdown('idProof3', $document,'', 'class= "form-control"'); ?> <input type="file" name="userfile[]" id="userfile" size="20" />
<button class="btn btn-white" type="submit">Cancel</button>
<button class="btn btn-primary" type="submit">Save changes</button>
Please guide me where i am doing wrong, if anyone have idea.
Thank You
I have done it with the help of below code:
in view i did made the name attribute as array <?php echo form_dropdown('idProof[]', $document,'', 'class= "form-control"'); ?>
in model i modified the function something like this:
public function upload_doc()
{
if(isset($_FILES['userfile']))
{
$name_array = array();
$count = count($_FILES['userfile']['size']);
$time=time();
$id = $this->db->insert_id();
$doc=$this->input->post('idProof');
$j = 0;
foreach($_FILES as $key=>$value)
for($s=0; $s<=$count-1; $s++)
{
$_FILES['userfile']['name'] = $id."_".$doc[$j]."_".$time."_".$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'] = './userData/';
$config['allowed_types'] = 'gif|jpg|png|doc|docx|pdf';
$config['max_size'] = '';
$config['max_width'] = '';
$config['max_height'] = '';
$this->load->library('upload', $config);
$this->upload->do_upload();
$data = $this->upload->data();
$name_array[] = $data['file_name'];
$j++;
}
//$names= implode(',', $name_array);
//$doc=$this->input->post('idProof');
//die();
$documentType[] = $this->input->post('idProof');
$keyIndex=0;
foreach($name_array as $name)
{
$db_data = array(
'documentType' => $doc[$keyIndex],
'image' => $name,
'customerId' => $id
);
$this->db->insert('document',$db_data);
$keyIndex++;
}
//print_r($db_data);
//die();
//die();
//print_r($names);
}
Thank you for the suggestions guys i made it work from it..

Categories