Multiple files upload in Codeigniter - php

I want to upload multiple files using single element. So I try this example.
Multiple files upload (Array) with CodeIgniter 2.0
This is my form
<form enctype="multipart/form-data" class="jNice" accept-charset="utf-8" method="post" action="http://xxxx.dev/admin/add_estates">
<fieldset>
<label>Title * : </label>
<input type="text" class="text-long" value="" name="title">
<label>Description : </label>
<textarea class="mceEditor" rows="10" cols="40" name="description"></textarea>
<label>Image : </label>
<input type="file" multiple="" name="images[]">
<button class="button-submit" type="submit" name="save" id="">Save</button>
</fieldset>
</form>
This is my controller
public function add_estates()
{
$data['page_title'] = "© IDEAL - Administrator - Real State - Add Real Estate";
$data['main_content'] = 'admin/add_estates';
if ($this->input->post() !== FALSE) {
$this->load->library('form_validation');
$this->form_validation->set_rules('title', 'Career Title', 'trim|required');
if ($this->form_validation->run() !== FALSE) {
$title = $this->input->post('title');
$description = $this->input->post('description');
if (!empty($_FILES['images']['name'][0])) {
if ($this->upload_files($title, $_FILES['images']) === FALSE) {
$data['error'] = $this->upload->display_errors('<div class="alert alert-danger">', '</div>');
}
}
if (!isset($data['error'])) {
$this->admin_model->add_estate($title, $description, $image_name);
$this->session->set_flashdata('suc_msg', 'New real estate added successfully');
redirect('admin/add_estates');
}
}
}
$data['suc_msg'] = $this->session->flashdata('suc_msg');
$this->load->view('layout_admin', $data);
}
This is my file upload method
private function upload_files($title, $files)
{
$config = array(
'upload_path' => './upload/real_estate/',
'allowed_types' => 'jpg|gif|png',
'overwrite' => 1,
);
$this->load->library('upload', $config);
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];
$config['file_name'] = $title .'_'. $image;
$this->upload->initialize($config);
if ($this->upload->do_upload($image)) {
$this->upload->data();
} else {
return false;
}
}
return true;
}
But it give You did not select a file to upload. every time. What is the issue?

I change upload method with images[] according to #Denmark.
private function upload_files($path, $title, $files)
{
$config = array(
'upload_path' => $path,
'allowed_types' => 'jpg|gif|png',
'overwrite' => 1,
);
$this->load->library('upload', $config);
$images = array();
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];
$fileName = $title .'_'. $image;
$images[] = $fileName;
$config['file_name'] = $fileName;
$this->upload->initialize($config);
if ($this->upload->do_upload('images[]')) {
$this->upload->data();
} else {
return false;
}
}
return $images;
}

You should use this library for multi upload in CI
https://github.com/stvnthomas/CodeIgniter-Multi-Upload

public function index() {
$user = $this->session->userdata("username");
$file_path = "./images/" . $user . '/';
if (isset($_FILES['multipleUpload'])) {
if (!is_dir('images/' . $user)) {
mkdir('./images/' . $user, 0777, TRUE);
}
$files = $_FILES;
$cpt = count($_FILES ['multipleUpload'] ['name']);
for ($i = 0; $i < $cpt; $i ++) {
$name = time().$files ['multipleUpload'] ['name'] [$i];
$_FILES ['multipleUpload'] ['name'] = $name;
$_FILES ['multipleUpload'] ['type'] = $files ['multipleUpload'] ['type'] [$i];
$_FILES ['multipleUpload'] ['tmp_name'] = $files ['multipleUpload'] ['tmp_name'] [$i];
$_FILES ['multipleUpload'] ['error'] = $files ['multipleUpload'] ['error'] [$i];
$_FILES ['multipleUpload'] ['size'] = $files ['multipleUpload'] ['size'] [$i];
$this->upload->initialize($this->set_upload_options($file_path));
if(!($this->upload->do_upload('multipleUpload')) || $files ['multipleUpload'] ['error'] [$i] !=0)
{
print_r($this->upload->display_errors());
}
else
{
$this->load->model('uploadModel','um');
$this->um->insertRecord($user,$name);
}
}
} else {
$this->load->view('uploadForm');
}
}
public function set_upload_options($file_path) {
// upload an image options
$config = array();
$config ['upload_path'] = $file_path;
$config ['allowed_types'] = 'gif|jpg|png';
return $config;
}

private function upload_files($path, $title, $files)
{
$config = array(
'upload_path' => $path,
'allowed_types' => 'jpg|gif|png',
'overwrite' => 1,
);
$this->load->library('upload', $config);
$images = array();
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];
$fileName = $title .'_'. $image;
$images[] = $fileName;
$config['file_name'] = $fileName;
$this->upload->initialize($config);
if ($this->upload->do_upload('images[]')) {
$this->upload->data();
} else {
return false;
}
}
return true;
}

<?php
if(isset($_FILES[$input_name]) && is_array($_FILES[$input_name]['name'])){
$image_path = array();
$count = count($_FILES[$input_name]['name']);
for($key =0; $key <$count; $key++){
$_FILES['file']['name'] = $_FILES[$input_name]['name'][$key];
$_FILES['file']['type'] = $_FILES[$input_name]['type'][$key];
$_FILES['file']['tmp_name'] = $_FILES[$input_name]['tmp_name'][$key];
$_FILES['file']['error'] = $_FILES[$input_name]['error'][$key];
$_FILES['file']['size'] = $_FILES[$input_name]['size'][$key];
$config['file_name'] = $_FILES[$input_name]['name'][$key];
$this->upload->initialize($config);
if($this->upload->do_upload('file')) {
$data = $this->upload->data();
$image_path[$key] = $path ."$data[file_name]";
}else{
$error = $this->upload->display_errors();
$this->session->set_flashdata('msg_error',"image upload! ".$error);
}
}
return json_encode($image_path);
}
?>

Related

Codeigniter : file uploading through mobile

i am using following code to upload the file .
$this->load->library('upload');
$files = $_FILES;
$cpt = count($_FILES['userfile']['name']);
$this->data['data']= $files;
$this->upload->initialize($this->set_upload_options());
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->data['name']= $_FILES['userfile']['name'];
$this->data['type']= $_FILES['userfile']['type'];
if($this->upload->do_upload()){
$this->db->insert('attachment', array(
'type' => 'quotation',
'typeid' => $lastid,
'path' => $_FILES['userfile']['name'],
'extension' => $_FILES['userfile']['type'],
));
$this->data['message'] = 'File Uplaoded';
}
else {
$this->data['message'] = $this->upload->display_errors();
}
}
echo json_encode($this->data); die;
private function set_upload_options()
{
//upload an image options
$config = array();
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png|mp4|jpeg';
$config['max_size'] = '*';
$config['overwrite'] = FALSE;
return $config;
}
Following is the output that we get in
data = {
userfile = {
error = 0;
name = imgname;
size = 146245;
"tmp_name" = "/tmp/phppYlH8A";
type = "image/jpeg";
};
};
message = "<p>You did not select a file to upload.</p>";
name = s;
type = i;
This is what mobile developer gets in response .
if i try following for files get uploaded
<form action="formlink" method="post" accept-charset="utf-8" enctype="multipart/form-data">
<input type="file" name="userfile[]" />
<input type="file" name="userfile[]" />
<br /><br />
<input type="submit" value="upload" />
</form>
please help me how can we fix this
You need to use below code for uploading the data:
$config = array(
'upload_path' => $path,
'allowed_types' => 'jpg|gif|png|jpeg',
'overwrite' => 1,
);
$this->load->library('upload', $config);
$images = array();
foreach ($files['name'] as $key => $image) {
if ($image != '') {
$_FILES['userfile[]']['name'] = $files['name'][$key];
$_FILES['userfile[]']['type'] = $files['type'][$key];
$_FILES['userfile[]']['tmp_name'] = $files['tmp_name'][$key];
$_FILES['userfile[]']['error'] = $files['error'][$key];
$_FILES['userfile[]']['size'] = $files['size'][$key];
$image = str_replace(' ', '_', $image);
$fileName = time() . '_' . $image;
$images[] = $fileName;
$config['file_name'] = $fileName;
$this->upload->initialize($config);
if ($this->upload->do_upload('images[]')) {
$this->upload->data();
} else {
return false;
}
}
}

How to upload video and audio file and save folder in codeigniter

<?php
public function videoupld()
{
$this->load->helper('string');
$config['upload_path'] = 'assets/upload/video'; # check path is correct
$config['max_size'] = '102400000';
$config['allowed_types'] = 'mp4'; # add video extenstion on here
$config['overwrite'] = FALSE;
$config['remove_spaces'] = TRUE;
$video_name =$_FILES['video_image']['name'];`
$config['file_name'] = $video_name;
$this->load->library('upload', $config);
$this->upload->initialize($config);
if ( ! $this->upload->do_upload('video_image'))
{
echo 'fail';
return;
//redirect('Admin/video_upload');
}
else
{
$data = array('upload_data' => $this->upload->data());
$this->load->view('upload_success', $data);
$url = 'assets/upload/video'.$video_name;
$this->Admin_model->videoupld($url);
redirect('Admin/video_upload');
}
}
?>
model
public function videoupld($url)
{
$title = $this->input->post('video_image');
//$details = $this->input->post('details');
//$type = $this->input->post('gallery');
$data = array(
'title' => $title,
'url' => $url,
//'category' => $type`
);
$this->db->insert('videoss', $data);
}
$uploaded = $this -> upload -> do_upload('video_image');
//here you will receive the object that you uploaded
// you will test if the file exist if yes the variable $file will recieve the full path
if ($uploaded) {
if ($data['file_ppt'] != '') {
$file = 'uploads/ppt/' . $data['file_ppt']; //full path
if (file_exists($file)) {
unlink($file);
}
}
}
//if file uploaded
//$save['file_ppt'] will have the name of the file uploaded
if ($uploaded) {
$file_ppt = $this -> upload -> data();
$save['file_ppt'] = $file_ppt['file_name'];
}
$uploaded = $this -> upload -> do_upload('video_image');
if ($uploaded) {
if ($data['file_ppt'] != '') {
$file = 'uploads/ppt/' . $data['file_ppt'];
if (file_exists($file)) {
unlink($file);
}
}
}
if ($uploaded) {
$file_ppt = $this -> upload -> data();
$save['file_ppt'] = $file_ppt['file_name'];
}
$this->db->insert('videoss', $save);
put this in the view :
and in controller : $names ="";
$name_array = array();
if(isset($_FILES['file_ppt'])){
$count = count($_FILES['file_ppt']['size']);
}else{
$count=0;
}
foreach($_FILES as $key=>$value)
for($s=0; $s<=$count-1; $s++) {
$_FILES['file_ppt']['name']=md5(time())."".$value['name'][$s];
$_FILES['file_ppt']['type'] = $value['type'][$s];
$_FILES['file_ppt']['tmp_name'] = $value['tmp_name'][$s];
$_FILES['file_ppt']['error'] = $value['error'][$s];
$_FILES['file_ppt']['size'] = $value['size'][$s];
// $config['allowed_types'] = 'gif|jpg|png';
$config['upload_path'] = 'uploads/messages';
$config['allowed_types'] = '*';
$config['max_size'] = '200000';
$this->load->library('upload', $config);
$uploaded = $this->upload->do_upload('file_ppt');
$data = $this->upload->data();
$names = $names.','.$_FILES['file_ppt']['name'];
}
if ($uploaded) {
// $file_ppt = $this -> upload -> data();
$save['file_ppt'] = $names;
// print_r('file ppt'.$file_ppt['file_name']);
}else {
echo $this->upload->display_errors();
}

can't upload image codeigniter

I am trying to upload an image.
Here is the code
<?php
$PerpetualCalendar = $this->input->post();
if($files['imgQuarter1']['name'][$key]!="")
{
$_FILES['imgQuarter1']['name']= $files['imgQuarter1']['name'][$key];
$_FILES['imgQuarter1']['type']= $files['imgQuarter1']['type'][$key];
$_FILES['imgQuarter1']['tmp_name']= $files['imgQuarter1']['tmp_name'][$key];
$_FILES['imgQuarter1']['error']= $files['imgQuarter1']['error'][$key];
$_FILES['imgQuarter1']['size']= $files['imgQuarter1']['size'][$key];
if(isset($PerpetualCalendar['id1'][$key]))
{
$img_id=$PerpetualCalendar['id1'][$key];
}
else
{
$img_id=$GetLastID;
}
$fileName = $img_id.'_NAME_'. $files['imgQuarter1']['name'][$key];
$config['file_name'] = $fileName;
$this->upload->initialize($config);
if($this->upload->do_upload('imgQuarter1'))
{
if(isset($PerpetualCalendar['NAMEpath_idQ1'][$key])){
$ImgUpdate[$imgkey]['tbl_name']='perpetual_calendar';
$ImgUpdate[$imgkey]['field_name']='event_name';
$ImgUpdate[$imgkey]['user_FK']=$user_id;
$ImgUpdate[$imgkey]['path']=$uploadpath.'/'.$fileName;
$ImgUpdate[$imgkey]['entry_id']=$img_id;
$ImgUpdate[$imgkey]['path_id']=$PerpetualCalendar['NAMEpath_idQ1'][$key]; //for update purpose
}else{
$ImgInsert[$imgkey]['tbl_name']='perpetual_calendar';
$ImgInsert[$imgkey]['field_name']='event_name';
$ImgInsert[$imgkey]['user_FK']=$user_id;
$ImgInsert[$imgkey]['path']=$uploadpath.'/'.$fileName;
$ImgInsert[$imgkey]['entry_id']=$img_id;
}
$imgkey++;
}
else
{
$this->data['error'] = $this->session->set_flashdata(array('error' => $this->upload->display_errors()));
}
}
?>
here is the View
echo form_upload(array('name'=>'imgQuarter1['.$key.']','class'=>'default'),'');
echo form_input(array('name' => 'id1['.$key.']', 'type'=>'hidden','value'=>$ValuePerpetualCalendar['cal_id']));
in above code,i can get $PerpetualCalendar['id1'][$key] this Id,but
image can not upload in the folder and can't save in Database Aswell !
Any Help?
public function upload_multiple_image($user_id){
$image = $_FILES['image']['name'];
$files = $_FILES['image'];
$image_title = $this->input->post('image_title');
$image_link = $this->input->post('image_link');
foreach($image as $key=>$data){
if($files['name'][$key]!=""){
$add_data['user_id'] = $user_id;
$add_data['title'] = $image_title[$key];
$add_data['description'] = $image_link[$key];
$add_data['status'] = 1;
$this->db->insert('user_images',$add_data);
$last_inserted_id = $this->db->insert_id();
$_FILES['image']['name'] = $files['name'][$key];
$_FILES['image']['type'] = $files['type'][$key];
$_FILES['image']['tmp_name'] = $files['tmp_name'][$key];
$_FILES['image']['error'] = $files['error'][$key];
$_FILES['image']['size'] = $files['size'][$key];
$config['upload_path'] = './user_images/original/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['overwrite'] = TRUE;
$config['file_name'] = 'place_image_'.$last_inserted_id;
$this->load->library('upload', $config);
$this->upload->initialize($config);
if($this->upload->do_upload('image')){
$file_details = $this->upload->data();
$update_data = array('image'=>$file_details['file_name']);
$this->db->update('user_images',$update_data,array('id'=>$last_inserted_id));
}
}
}
}

Image upload not working in codeigniter

i am trying to upload multiple images using codeigniter. But images are not uploaded to the upload_images folder.
no errors are shown.
View form
<form action="<?php echo base_url(); ?>property/add_images2" method="post" enctype="multipart/form-data">
<input type="file" name="files1" multiple="multiple" accept="image/*">
<div id="image">
</div>
<a id="another_image" href="#">Add Another Image</a>
<input type="submit" value="Upload">
</form>
jquery
<script type="text/javascript">
$(document).ready(function(){
var count = 2;
$('#another_image').click (function(){
if(count < 7){
$('<input type="file" name="files'+count+'" multiple="multiple" accept="image/*">').appendTo ("#image");
count++;
}
});
});
</script>
Controller
function add_images2(){
$this->load->library('upload');
$files = $_FILES;
if($files){
for( $i = 1; $i < 7; $i++) {
$config = array();
$config['upload_path'] = './upload_images/';
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$config['max_size'] = '10000';
$config['file_name'] = 'prop_'.md5(time());
$config['overwrite'] = FALSE;
$this->load->library('upload', $config);
$this->upload->do_upload('files'.$i);
}
}
$this->load->view('add_images2');
}
don't know where i made the mistake.
Tnx..
Write the below Function in your Controller.
/*It will upload the images to the specified path and will return the image urls in an array*/
private function upload_files($path, $files)
{
$path = PHYSICAL_PATH . $path;
$config = array(
'upload_path' => $path,
'allowed_types' => 'JPG|JPEG|GIF|PNG|gif|jpg|png|jpeg|tft|TFT',
'overwrite' => 1,
);
$this->load->library('upload', $config);
$images = array();
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];
$fileName = time() .'_'. $image;
$images[] = $fileName;
$config['file_name'] = $fileName;
$this->upload->initialize($config);
if ($this->upload->do_upload('images[]')) {
$this->upload->data();
} else {
echo $this->upload->display_errors();die();
return false;
}
}
return $images;
}
call the above Function in your function
$firstFileName = $_FILES['photo']['name'][0];//Check whether any Images is uploaded or not.
if($firstFileName != "")
{
$path = "uploads/property_image/";//Give your Path name
$values = $this->upload_files($path,$_FILES['photo']);
/* $values contents the Image path Array.Now you can send the array to the View Page for your use or can call any Models to store into the DB. */
}

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

Categories