Multiple image upload with CodeIgniter - php

I am new user to using code igniter in my project, I am facing one problem while uploading multiple files but the last one only insert to all image three images field.
my controller is:
function products()
{
date_default_timezone_set("Asia/Kolkata");
$config['upload_path'] = './resources/images/products/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 1000;
$config['max_width'] = 1024;
$config['max_height'] = 768;
$this->load->library('upload', $config);
$this->upload->do_upload('userfile');
$data = array('prod_image' => $this->upload->data(),
'prod_image1' => $this->upload->data(),
'prod_image2' => $this->upload->data());
$product_image=$data['prod_image']['file_name'];
$product_image1=$data['prod_image1']['file_name'];
$product_image2=$data['prod_image2']['file_name'];
$data = array(
'name' => $this->input->post('pd_name'),
'prod_image' => $product_image,
'prod_image1' => $product_image1,
'prod_image2' => $product_image2,
'created_time' => date('Y-m-d H:i:s'));
// insert form data into database
$result_set= $this->tbl_products_model->insertUser($data);
}
my view part is:
<input class="form-control" name="pd_name"type="text"/>
<input type="file" class="file_upload2" name="userfile"/> //1
<input type="file" class="file_upload2" name="userfile"/> //2
<input type="file" class="file_upload2" name="userfile"/>//3
Please help how to insert 3 images.
my datad base like
===========================================
id|name|prod_image|prod_image1|prod_image2|
===========================================
1|ard| | | |
============================================

Html :
<input type="file" name="userfile[]" multiple="multiple">
PHP :
<?php
public function products()
{
$this->load->library('upload');
$dataInfo = array();
$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('userfile');
$dataInfo[] = $this->upload->data();
}
$data = array(
'name' => $this->input->post('pd_name'),
'prod_image' => $dataInfo[0]['file_name'],
'prod_image1' => $dataInfo[1]['file_name'],
'prod_image2' => $dataInfo[2]['file_name'],
'created_time' => date('Y-m-d H:i:s')
);
$result_set = $this->tbl_products_model->insertUser($data);
}
private function set_upload_options()
{
//upload an image options
$config = array();
$config['upload_path'] = './resources/images/products/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '0';
$config['overwrite'] = FALSE;
return $config;
}
?>

Multiple files uploads unlimited files
Database table(profile_images) column names are image_name(255,varcher), added_datetime(current timestamp)
View
<?php echo validation_errors();?>
<?php echo form_open_multipart('pages/multiple_files');?>
<p><input type="file" multiple="multiple" name="image_name[]" class="form-control" /></p>
<input type="submit" class="btn btn-success btn-block"/>
</form>
Controller
public function multiple_files(){
$this->load->library('upload');
$image = array();
$ImageCount = count($_FILES['image_name']['name']);
for($i = 0; $i < $ImageCount; $i++){
$_FILES['file']['name'] = $_FILES['image_name']['name'][$i];
$_FILES['file']['type'] = $_FILES['image_name']['type'][$i];
$_FILES['file']['tmp_name'] = $_FILES['image_name']['tmp_name'][$i];
$_FILES['file']['error'] = $_FILES['image_name']['error'][$i];
$_FILES['file']['size'] = $_FILES['image_name']['size'][$i];
// File upload configuration
$uploadPath = './assets/images/profiles/';
$config['upload_path'] = $uploadPath;
$config['allowed_types'] = 'jpg|jpeg|png|gif';
// Load and initialize upload library
$this->load->library('upload', $config);
$this->upload->initialize($config);
// Upload file to server
if($this->upload->do_upload('file')){
// Uploaded file data
$imageData = $this->upload->data();
$uploadImgData[$i]['image_name'] = $imageData['file_name'];
}
}
if(!empty($uploadImgData)){
// Insert files data into the database
$this->pages_model->multiple_images($uploadImgData);
}
}
Model
public function multiple_images($image = array()){
return $this->db->insert_batch('profile_images',$image);
}

The problem is with the following line of code:
<input type="file" class="file_upload2" name="userfile"/> //1
<input type="file" class="file_upload2" name="userfile"/> //2
<input type="file" class="file_upload2" name="userfile"/>//3
These all three have same name.
To solve this there are two ways:
Give diff name to all 3 input type file
Make a single input type file with its multiple file selection true and its name must be an array like:
<input type="file" name="filefield[]" multiple="multiple">
Make the following changes and try again.

code of controller.
public function upload_multiple($field_name,$path){
$this->load->library('upload');
$files = $_FILES;
$cpt = count($_FILES[$field_name]['name']);//count for number of image files
$image_name =array();
for($i=0; $i<$cpt; $i++)
{
$_FILES[$field_name]['name']= $files[$field_name]['name'][$i];
$_FILES[$field_name]['type']= $files[$field_name]['type'][$i];
$_FILES[$field_name]['tmp_name'] = $files[$field_name]['tmp_name'][$i];
$_FILES[$field_name]['error']= $files[$field_name]['error'][$i];
$_FILES[$field_name]['size'] = $files[$field_name]['size'][$i];
$this->upload->initialize($this->set_upload_options($path));
//for initalizing configuration for each image
$this->upload->do_upload($field_name);
$data = array('upload_data' => $this->upload->data());
$image_name[]=$data['upload_data']['file_name'];
//store file name into array
}
return $image_name;//all images name which is uploaded
}
public function set_upload_options($path)
{
$config = array();
$config['upload_path'] = $path;
$config['allowed_types'] = '*';
$config['overwrite'] = FALSE;
return $config;
}
call function
$image_name=$this->upload_multiple('profile_image',$path=USER_OTHER);//we get all name of uploaded file in $image_name array.

Related

I am getting only first image in an array while uploading file, I want all images in array.Using Codeigniter

Here I am attaching the code of the desires problem.
Cotroller has following code.
Controller=>
//Load upload library
$this->load->library('upload');
$images = array();
$i = 0;
foreach ($_FILES as $key => $value)
{
$tmp = explode(".",$value['name'][$i]);
$imagename = time().".".end($tmp);
$_FILES['file']['name'] = $imagename;
$_FILES['file']['type'] = $value['type'][$i];
$_FILES['file']['tmp_name'] = $value['tmp_name'][$i];
$_FILES['file']['error'] = $value['error'][$i];
$_FILES['file']['size'] = $value['size'][$i];
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['file_name'] = $imagename;
$this->upload->initialize($config);
if ( ! $this->upload->do_upload('file'))
{
$error = array($i => $this->upload->display_errors());
echo "<pre>";print_r($error);die;
}
else
{
array_push($images,$this->upload->data()['file_name']);
}
$i++;
}
echo "<pre>";print_r($images);die;
This is a form code that I am using while uploading file.
View =>
<?php $attributes = array(
"class" => "form-horizontal m-t-20",
"method" => "post",
"novalidate" => "",
"enctype" => "multipart/form-data"
);
echo form_open('admin/user/adduser', $attributes); ?>
Here is my file input control.
<label for="file">Profile Images*</label>
<input type="file" name="files[]" id="file" multiple required placeholder="Profile Images" class="form-control">
Change your code as follows
foreach($_FILES["files"]["tmp_name"] as $key=>$value) {
and change $i to the $key as follows (apply to the all)
$_FILES['file']['type'] = $_FILES["files"]['type'][$key];
As wazabii suggested, attached some random string to the file name. You can use rand(100,10000)
That is because the time() will be the same on all the images, so the file name is not unique. This is easily fixed by adding the array key to the file name.
$tmp = explode(".",$value['name'][$i]);
$imagename = time()."-".$key.".".end($tmp);
contoller code
public function upload_multiple($field_name,$path){
$this->load->library('upload');
$files = $_FILES;
$cpt = count($_FILES[$field_name]['name']);//count for number of image files
$image_name =array();
for($i=0; $i<$cpt; $i++)
{
$_FILES[$field_name]['name']= $files[$field_name]['name'][$i];
$_FILES[$field_name]['type']= $files[$field_name]['type'][$i];
$_FILES[$field_name]['tmp_name'] = $files[$field_name]['tmp_name'][$i];
$_FILES[$field_name]['error']= $files[$field_name]['error'][$i];
$_FILES[$field_name]['size'] = $files[$field_name]['size'][$i];
$this->upload->initialize($this->set_upload_options($path));//for initalizing configuration for each image
$this->upload->do_upload($field_name);
$data = array('upload_data' => $this->upload->data());
$image_name[]=$data['upload_data']['file_name'];//store file name to store in database
}
return $image_name;//all images name which is uploaded
}
public function set_upload_options($path)
{
$config = array();
$config['upload_path'] = $path;
$config['allowed_types'] = 'gif|jpg|png';
$config['overwrite'] = FALSE;
return $config;
}
function call
$image_name=$this->upload_multiple('portfolio_image',$path);//for multiple image upload
input field
<input type="file" id="portfolio_image" name="protfolio_image[]" >

Upload multiple image doesn't store to databased and path folder

I'm making upload multiple image and stored to one field. But I have a proble with my code, images can't store to database and to path folder. May be you can help me please
This is my controller
public function post() {
if(empty($_FILES['file']['name'])) {
$data = array( 'id_merk' => $this->input->post('id_merk'),
'createdAt' => $this->input->post('createdAt')
);
// var_dump($data);
$this->m_barang->post( $data );
$this->session->set_flashdata('success', 'success');
redirect('admin/merk');
} else {
$count = count($_FILES['file']['size']);
foreach($_FILES as $value){
for($s=0; $s<=$count-1; $s++) {
$_FILES['file']['name'] = $value['name'][$s];
$_FILES['file']['type'] = $value['type'][$s];
$_FILES['file']['tmp_name'] = $value['tmp_name'][$s];
$_FILES['file']['error'] = $value['error'][$s];
$_FILES['file']['size'] = $value['size'][$s];
// $config['file_name'] = 'pict_'.date('Y_m_d_H_i_s').'.jpg';
$config['upload_path'] = './upload/be/barang';
$config['allowed_types'] = 'gif|GIF|jpg|JPG|jpeg|JPEG|png|PNG';
$config['max_size'] = '8000';
$config['max_width'] = '1366';
$config['max_height'] = '1024';
$this->load->library('upload', $config);
$this->upload->do_upload();
$data = $this->upload->data();
$name_array[] = $data['file_name'];
}
}
$names = implode(', ', $name_array);
$data = array( 'id_merk' => $this->input->post('id_merk'),
'photo_barang' => $names
);
$this->m_barang->post( $data );
$this->session->set_flashdata('success', 'gambar ada');
redirect('admin/merk');
}
}
and this is my view
<input class="form-control" name="file[]" id="files" type="file" multiple="multiple">
Please, can you help me how to fix my problem with my code?
First, Use only 1 loop to upload the multiple images.
Second, give name attribute of <input type="file"> to $this->upload->do_upload()
Third, if uploading path inside the application folder then use APPPATH.'upload/be/barang' or if outside the application folder use FCPATH.'upload/be/barang'
$count = count($_FILES['file']['size']);
for($s=0; $s<=$count-1; $s++) {
$_FILES['file']['name'] = $_FILES['file']['name'][$s];
$_FILES['file']['type'] = $_FILES['file']['type'][$s];
$_FILES['file']['tmp_name'] = $_FILES['file']['tmp_name'][$s];
$_FILES['file']['error'] = $_FILES['file']['error'][$s];
$_FILES['file']['size'] = $_FILES['file']['size'][$s];
$config['upload_path'] = './upload/be/barang';
$config['allowed_types'] = 'gif|GIF|jpg|JPG|jpeg|JPEG|png|PNG';
$config['max_size'] = '8000';
$config['max_width'] = '1366';
$config['max_height'] = '1024';
$this->load->library('upload', $config);
if(!$this->upload->do_upload('file')){
//image uploading error
}else{
$data = $this->upload->data();
$name_array[] = $data['file_name'];
}
}

Codeigniter file upload displaying error

Controller code
$config['upload_path'] = './uploads/'.$random;
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 100;
$config['max_width'] = 1024;
$config['max_height'] = 768;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('imageupload'))
{
$error = array('error' => $this->upload->display_errors());
}
else
{
$data = array('upload_data' => $this->upload->data());
}
print_r($data);
HTML code:
<form role="form" enctype="multipart/form-data" accept-charset="utf-8" name="formname" id="formname" method="post" action="http://www.example.com/Property/post">
<input type="file" class="default" id="imageupload1" name="imageupload[]">
</form>
Whenever I am uploading file it displaying warning is_uploaded_file() expects parameter 1 to be string, array given. How can I resolve it?
try this
//place this code in your function for multiple image upload
$data = array();
if(!empty($_FILES['imageupload']['name']))
{
$filesCount = count($_FILES['imageupload']['name']);
for($i = 0; $i < $filesCount; $i++){
$_FILES['imageupload']['name'] = $_FILES['imageupload']['name'][$i];
$_FILES['imageupload']['type'] = $_FILES['imageupload']['type'][$i];
$_FILES['imageupload']['tmp_name'] = $_FILES['imageupload']['tmp_name'][$i];
$_FILES['imageupload']['error'] = $_FILES['imageupload']['error'][$i];
$_FILES['imageupload']['size'] = $_FILES['imageupload']['size'][$i];
$uploadPath = 'uploads/';
$config['upload_path'] = $uploadPath;
$config['allowed_types'] = 'gif|jpg|png';
$this->load->library('upload', $config);
$this->upload->initialize($config);
if($this->upload->do_upload('imageupload')){
$fileData = $this->upload->data();
$uploadData[$i]['file_name'] = $fileData['file_name'];
$uploadData[$i]['created'] = date("Y-m-d H:i:s");
$uploadData[$i]['modified'] = date("Y-m-d H:i:s");
}
}
if(!empty($uploadData)){
//Insert file into the database using your model
}
}
Probably your input name should be without brackets:
<input type="file" class="default" id="imageupload1" name="imageupload">

How to store the file in mysql database using codeigniter?

I have created a simple contact form.I want to store the file in database which is uploaded by any user.I am able to store the file in my folder but i have to store the file in database to identify the admin which file is upload.
Controller
public function index()
{
$this->load->view('demo', array('error' => ' ' ));
}
public function do_upload()
{
$id = $this->session->userdata('id');
$this->load->model('Model_doc');
$config['upload_path'] = './upload/';
$config['allowed_types'] = 'docx';
$config['max_size'] = 1000;
$config['max_width'] = 1024;
$config['max_height'] = 768;
$this->load->library('upload', $config);
$this->upload->do_upload();
$this->Model_doc->index($id, $this->upload->data());
}
Model
public function index($id,$imgdata)
{
$imgdata = file_get_contents($imgdata['../upload/']);
$data = array(
'path'=>$imgdata,
);
$this->db->set('curentDate', 'NOW()', FALSE);
$this->db->insert('test',$data);
}
View
<?php echo form_open_multipart('welcome/do_upload');?>
<input type="file" name="userfile" size="20" />
<br /><br />
<input type="submit" value="upload" />
</form>
Change code in the Controller File as Folow:
public function do_upload()
{
$id = $this->session->userdata('id');
$this->load->model('Model_doc');
$config['upload_path'] = './upload/';
$config['allowed_types'] = 'docx';
$config['max_size'] = 1000;
$config['max_width'] = 1024;
$config['max_height'] = 768;
$this->load->library('upload', $config);
$this->upload->do_upload();
$full_file_path = base_url()."/upload/".$_FILES['userfile']['name'];
//This Is Full Path of the file stored to your folder,Change it if required.
$this->Model_doc->index($id,$full_file_path);
}
Changes in the Model File:
public function index($id,$full_file_path)
{
$data = array(
'path'=>$full_file_path,
);
$this->db->set('curentDate', 'NOW()', FALSE);
$this->db->insert('test',$data);
}

How to upload multiple files in codeigniter 3.0.1

How to upload multiple files in codeigniter 3.0.1. There are similar issues and solutions in stackoverflow but unfortunately non of them are helping to fix the issue I am facing.
This is the error message appearing You did not select a file to upload with my current code
view (addGallery)
<section>
<h2>Add Gallery</h2>
<?php echo form_open('Newsupload/gallery', ['id'=>'news', 'name'=>'news', 'method'=>'post','enctype'=>'multipart/form-data']) ?>
<div class="grp width-50">
<label for="name">Album Name</label>
<input type="text" name="name" id="name" value="" placeholder="">
</div>
<div class="grp width-100">
<div id="selectedFiles"></div>
<input type="file" id="files" name="files[]" multiple size="20"><br/>
</div>
<?php if (isset($error)) {
echo $error;
} ?>
<grp class="grp width-100">
<button>Add</button>
</grp>
</form>
</section>
controller (gallery)
public function gallery()
{
$this->load->library('upload');
$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];
$this->upload->initialize($this->set_upload_options());
// $this->upload->do_upload('files[]');
if (!$this->upload->do_upload('files[]'))
{
$error =['error' => $this->upload->display_errors()];
$this->load->view('admin/addGallery', $error);
}
}
}
public function set_upload_options()
{
$config['upload_path'] = getcwd().'/upload/';
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$config['remove_spaces'] = true;
return $config;
}
By default codeIgniter doesn't support multi-file upload. So you can use
this library CodeIgniter Multiple Upload Library
I think you need to change this line:
if (!$this->upload->do_upload('files[]'))
to
if (!$this->upload->do_upload('files'))
you did not pass file name to upload function.Try this.
if (!$this->upload->do_upload($_FILES['files']['name']))
{
$error =['error' => $this->upload->display_errors()];
$this->load->view('admin/addGallery', $error);
}
try this:
$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];
$this->upload->initialize($this->set_upload_options());
$this->upload->do_upload();
$fileName = $_FILES['files']['name'];
$images[] = $fileName;
and make a function set_upload_options()
$config = array();
$config['upload_path'] = './upload/'; //give the path to upload the image in folder
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '0';
$config['overwrite'] = FALSE;
return $config;
For more Upload multiple files using codeigniter try this http://w3code.in/2015/09/upload-file-using-codeigniter/
Please try bellow
for($i=0; $i<$cpt; $i++)
{
$_FILES['files'] = $files[$i];
$this->upload->initialize($this->set_upload_options());
if (!$this->upload->do_upload('files'))
{
$error =['error' => $this->upload->display_errors()];
$this->load->view('admin/addGallery', $error);
}
}
You can upload multiple files with CodeIgniter in a single request. You just need to do do_upload() for each file. Here's one implementation. You can work it into a loop if needed.
// Image upload Config
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$config['max_size'] = '1000000';
$config['encrypt_name'] = TRUE;
$this->load->library('upload', $config);
// Upload Files
if ( $_FILES['first_file']['name'] && $this->upload->do_upload('first_file') ) {
$first_file = $this->upload->data();
}
if ( $_FILES['second_file']['name'] && $this->upload->do_upload('second_file') ) {
$second_file= $this->upload->data();
}
Just that i understood from the library $this->upload->do_upload('inputelementname') doesn't have to be input element name. It should be the key of files array.
So in this context this should work
if($_FILES){
$filecount=count($_FILES['addmediaelement']['name']);
for($i=0; $i<$filecount; $i++){
$_FILES['mediaelement']['name']=$_FILES['addmediaelement']['name'][$i];
$_FILES['mediaelement']['type']=$_FILES['addmediaelement']['type'][$i];
$_FILES['mediaelement']['tmp_name']=$_FILES['addmediaelement']['tmp_name'][$i];
$_FILES['mediaelement']['error']=$_FILES['addmediaelement']['error'][$i];
$_FILES['mediaelement']['size']=$_FILES['addmediaelement']['size'][$i];
$config['upload_path']=path/to/save/file;
$config['file_name']=filealternatename.extension;
$config['max_size']=MAXSIZE; //max size constant
$config['max_width']=MAXWIDTH; //max width constant
$config['max_height']=CMPMAXHEIGHT; //max height constant
$config['allowed_types']='jpg|png';
if(!is_dir($config['upload_path'])){
mkdir($config['upload_path'], 0775);
}
$this->upload->initialize($config);
$imageuploaderres[]=$this->upload->do_upload('mediaelement');
}
}

Categories