Cannot upload multiple file with CodeIgniter 3 - codeigniter

With my code below it can be uploaded just the single file but cannot upload multiple file please advise me what i am doing wrong.
Here is the error message.
Array ( [error] =>
You did not select a file to upload.
)
UPDATE MY QUESTION
when I do
echo $i.":".$_FILES['file_upload']['name'][$i].'<br/>';
Here is the result
0:heading-title-bg.jpg
1:varun.jpg
But after I changed the code to
$_FILES['file_upload']['name'] = $_FILES['file_upload']['name'][$i];
echo $i.":".$_FILES['file_upload']['name'].'<br/>';
Here is result :
0:heading-title-bg.jpg
1:e
//CONTROLLER
public function addPhoto(){
if (!empty($_FILES)):
$count = count($_FILES['file_upload']['name']);
for($i =0; $i<$count;$i++):
$_FILES['file_upload']['name'] = $_FILES['file_upload']['name'][$i];
$_FILES['file_upload']['type'] = $_FILES['file_upload']['type'][$i];
$_FILES['file_upload']['tmp_name'] = $_FILES['file_upload']['tmp_name'][$i];
$_FILES['file_upload']['error'] = $_FILES['file_upload']['error'][$i];
$_FILES['file_upload']['size'] = $_FILES['file_upload']['size'][$i];
$config['upload_path'] = './uploads/employee/';
$config['allowed_types'] = 'jpg|png';
$config['max_size'] = 5000;
$config['max_width'] = 0;
$config['max_height'] = 0;
$config['overwrite'] = FALSE;
$config['remove_spaces'] = TRUE;
$this->load->library('upload', $config);
$this->upload->initialize($config);
if($this->upload->do_upload('file_upload')){
$data = $this->upload->data();
echo "<pre>";
print_r($data);
echo "</pre>";
}else{
$error = array('error' => $this->upload->display_errors());
print_r($error);
}
endfor;
endif; //$_FILE
}
VIEW
<input type="file" name="file_upload[]" class="form-control-file" id="fileUpload" multiple>

This is working code in my project
$data = array();
$filesCount = count($_FILES['daily_records']['name']);
for($i = 0; $i < $filesCount; $i++){
$_FILES['daily_record']['name'] = $time."-".$_FILES['daily_records']['name'][$i];
$_FILES['daily_record']['type'] = $_FILES['daily_records']['type'][$i];
$_FILES['daily_record']['tmp_name'] = $_FILES['daily_records']['tmp_name'][$i];
$_FILES['daily_record']['error'] = $_FILES['daily_records']['error'][$i];
$_FILES['daily_record']['size'] = $_FILES['daily_records']['size'][$i];
$uploadPath = './assets/uploads/daily_records/daily_record';
$config['upload_path'] = $uploadPath;
$config['allowed_types'] = 'gif|jpg|png|pdf|docx';
//$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('daily_record')){
$fileData = $this->upload->data();
$file_name = $fileData['file_name'];
echo $file_name;
}
}

I have already fixed by myself.
Here is my final code now is work for me.
foreach ($_FILES as $key => $v) {
for ( $i = 0; $i < count($v['name']); $i++ ){
$_FILES['file_upload']['name'] = $v['name'][$i];
$_FILES['file_upload']['type'] = $v['type'][$i];
$_FILES['file_upload']['tmp_name'] = $v['tmp_name'][$i];
$_FILES['file_upload']['error'] = $v['error'][$i];
$_FILES['file_upload']['size'] = $v['size'][$i];
//echo $_FILES['file_upload']['name'] ;
if(! $this->upload->do_upload('file_upload')){
$error = array('error' => $this->upload->display_errors());
print_r($error);
}else{
$data = $this->upload->data();
echo "<pre>";
print_r($data);
echo "</pre>";
}
}
}

Related

Cannot set new image name in codeigniter

I'm uploading multiple image in codeigniter, But when i set new name using this code $_FILES['attachment']['name']= $filename;
I'm getting
The filetype you are attempting to upload is not allowed.
Please suggest solution to solve this issue.
public function do_upload()
{
if (($_SERVER['REQUEST_METHOD']) == "POST") {
$count = count($_FILES['attach_file']['name']);
$files = $_FILES;
for($i=0; $i<$count; $i++){
$filename = $_FILES['attach_file']['name'][$i];
$filename = strstr($filename, '.', true);
$email = $this->session->userdata('email');
$filename = strstr($email, '#', true)."_".$filename;
$filename = strtolower($filename);
$_FILES['attachment']['name']= $filename;
$_FILES['attachment']['type']= $_FILES['attach_file']['type'][$i];
$_FILES['attachment']['tmp_name']= $_FILES['attach_file']['tmp_name'][$i];
$_FILES['attachment']['error']= $_FILES['attach_file']['error'][$i];
$_FILES['attachment']['size']= $_FILES['attach_file']['size'][$i];
$config['upload_path'] = FCPATH .'./assets/attachments/new/';
$config['allowed_types'] = 'pdf|doc|docx|bmp|gif|jpg|jpeg|jpe|png';
$config['max_size'] = 0;
$config['max_width'] = 0;
$config['max_height'] = 0;
$config['encrypt_name'] = true;
$config['file_ext_tolower'] = true;
$config['overwrite'] = false;
$this->load->library('upload', $config);
if (!$this->upload->do_upload('attachment')) {
$data['exception'] = $this->upload->display_errors();
$data['status'] = false;
echo json_encode($data);
} else {
$upload = $this->upload->data();
$data['message'] = 'upload_successfully';
$data['filepath'] = './assets/attachments/'.$upload['file_name'];
$data['status'] = true;
echo json_encode($data);
}
}
}
}
Note:- You are assign same variable name again & again $filename
Please Change this:-
$filename = $_FILES['attach_file']['name'][$i];
$filename = strstr($filename, '.', true);
$email = $this->session->userdata('email');
$filename = strstr($email, '#', true)."_".$filename;
$filename = strtolower($filename);
$_FILES['attachment']['name']= $filename;
to :-
$filename = $_FILES['attach_file']['name'][$i];
$filename1 = strstr($filename, '.', true);
$email = $this->session->userdata('email');
$filename2 = strstr($email, '#', true)."_".$filename1;
$filename3 = strtolower($filename2);

How to use Multiple images in codeigniter

In my page I want user to select multiple images and upload it I am saving images name in database for reference. I am successful in uploading single images in database and can also show image in view but now I have problem in uploading multiple images.
public function add_record()
{
$this->form_validation->set_rules('category', 'category', 'required');
$current_date = date("Y-m-d H:i:s");
$error='';
if($this->form_validation->run())
{
$image = '';
if($_FILES['image']['name'])
{
if (!is_dir('/backend_assets/media/image/')) {
mkdir('./backend_assets/media/image/', 0777, TRUE);
}
$config['upload_path'] = './backend_assets/media/image/';
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$this->load->library('upload', $config);
$this->upload->initialize($config);
if ($this->upload->do_upload('image'))
{
$data = $this->upload->data();
$image = $data['file_name'];
}else{
$this->session->set_flashdata('error', $this->upload->display_errors());
redirect(base_url('admin/image'));
}
}
$insert_array = array(
'gl_cat_id' => $this->input->post('category'),
'gl_image'=> $image
);
if ($this->common_model->add_records('vm_image',$insert_array))
{
$id = $this->db->insert_id();
$insert_sco_details = array(
'sd_ty'=>'vm_image',
'sd_ty_id'=>$id,
'sd_image'=>$image
);
if($this->common_model->publication('vm_image',$id) && $this->common_model->add_records('vm_seo_detail',$insert_sco_details))
{
$this->session->set_flashdata('success','Record added successfully');
redirect(base_url('admin/image'));
}else{
$this->session->set_flashdata('error','Error while adding record');
redirect(base_url('admin/image'));
}
}else{
$this->session->set_flashdata('error','Error while adding record');
redirect(base_url('admin/image'));
}
}
$where_array = array('vm_publications.status !=' => 4);
$data['users_type'] = $this->common_model->get_records('vm_image_category','','','');
$data['include'] = 'backend/image/add_image';
$this->load->view('backend/container', $data);
}
How is it possible with above code...?
$current_date = date("Y-m-d H:i:s");
$error = '';
$image = '';
if(isset($_FILES['image']['name']))
{
//print_r($_FILES);
$id = base64_decode($this->input->post('gid'));
$filesCount = count($_FILES['image']['name']);
$inserted = '';
for($i = 0; $i < $filesCount; $i++)
{
$_FILES['userFile']['name'] = $_FILES['image']['name'][$i];
$_FILES['userFile']['type'] = $_FILES['image']['type'][$i];
$_FILES['userFile']['tmp_name'] = $_FILES['image']['tmp_name'][$i];
$_FILES['userFile']['error'] = $_FILES['image']['error'][$i];
$_FILES['userFile']['size'] = $_FILES['image']['size'][$i];
$config['upload_path'] = './backend_assets/media/image/';
$config['allowed_types'] = 'gif|jpg|png';
$this->load->library('upload', $config);
$this->upload->initialize($config);
if($this->upload->do_upload('userFile'))
{
$fileData = $this->upload->data();
$image = $fileData['file_name'];
$insert_array = array(
'gl_cat_id' => $this->input->post('category'),
'gl_image'=> $image
);
if ($this->common_model->add_records('vm_image',$insert_array))
{
$id = $this->db->insert_id();
$insert_sco_details = array(
'sd_ty'=>'vm_image',
'sd_ty_id'=>$id,
'sd_image'=>$image
);
if($this->common_model->publication('vm_image',$id) && $this->common_model->add_records('vm_seo_detail',$insert_sco_details))
{
$inserted++;
}
}
}
}
if($inserted == $filesCount)
{ $this->session->set_flashdata('success','Images uploaded successfully');
redirect(base_url('adminp8AamG6ueHFNGAAp/image'));
}else{
$this->session->set_flashdata('error','Error while adding record');
redirect(base_url('adminp8AamG6ueHFNGAAp/image'));
}
}
$where_array = array('vm_publications.status !=' => 4);
$data['users_type'] = $this->common_model->get_records('vm_image_category','','','');
$data['include'] = 'backend/image/add_image';
$this->load->view('backend/container', $data);
try below code in you add_record() function. it will helpful to you. few days ago, i have faced same problem
$files = $_FILES;
$count = count($_FILES['image']['name']);
for($i=0; $i<$count; $i++) {
$_FILES['image']['name']= $files['image']['name'][$i];
$_FILES['image']['type']= $files['image']['type'][$i];
$_FILES['image']['tmp_name']= $files['image']['tmp_name'][$i];
$_FILES['image']['error']= $files['image']['error'][$i];
$_FILES['image']['size']= $files['image']['size'][$i];
$this->upload->initialize($this->set_upload_options());//function defination below
$this->upload->do_upload('image');
$upload_data = $this->upload->data();
$name_array[] = $upload_data['file_name'];
$fileName = $upload_data['file_name'];
$images[] = $fileName;
}
$fileName = $images;
and set file upload configuration in set_upload_options function in same controller.
function set_upload_options() {
$config = array();
$config['upload_path'] = PATH;
$config['remove_spaces']=TRUE;
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '78000';
return $config;
}
First, debug the output of the $_FILES variable. This should give you an array of files that are being uploaded. Loop through them to treat each one individually.
foreach ($_FILES as $file) {
// do some file processing on the $file object instead of $_FILES object.
// example: instead of using 'if($_FILES['image']['name'])'
// use: 'if($file['image']['name'])'
}
If you want to use CI's upload class, check out their Docs here: https://www.codeigniter.com/userguide3/libraries/file_uploading.html

codeigniter upload files from multiple input

i want to upload files with multiple input. I have tried the code below, but the files not uploaded, and i cant get the upload directory.
HTML
<input type="file" name="userfile[]" size="20" />
Controller
public function detailTugasInput($idKelas,$id){
$this->load->model('tugass');
$records = $_FILES['userfile'];
//var_dump($records); die();
$config['upload_path'] = './file/';
$config['allowed_types'] = 'pdf|doc|txt|jpg|png';
$config['max_size'] = 0;
$config['max_width'] = 1024;
$config['max_height'] = 768;
$this->load->library('upload', $config);
foreach ($_FILES as $key => $value) {
$upload_data = $this->upload->data();
$file_ary = array(
'nama_kembali' => $value['name'],
'file_kembali' => $value['tmp_name']
);
}
}
And i also tried to get the uploaded data with this code below, but why always appear error?
$checked_arr = $_POST['userfile'];
Try Below Codes
HTML :
<input type="file" class="form-control" name="userfile[]" multiple />
Controller :
public function detailTugasInput($idKelas, $id){
$this->load->model('tugass');
if(!empty($_FILES['userfile']['name'])) {
$filesCount = count($_FILES['userfile']['name']);
for($i = 0; $i < $filesCount; $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];
$config['upload_path'] = './file/';
$config['allowed_types'] = 'pdf|doc|txt|jpg|png';
$this->load->library('upload', $config);
$this->upload->initialize($config);
$this->upload->do_upload('userFile');
if($this->upload->do_upload('userFile')){
$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");
}
}
}
}
For more Support, Check This

codeigniter success insert to database but failed to insert uploaded file

I'm new here, so nice to meet you all.
I have trouble with codeigniter.
Maybe hard to tell so I will show all of my code :
my controller :
function upload_barang(){
$this->admin_model->login();
$this->admin_model->valid_product();
$config['upload_path'] = './produk/';
$config['allowed_types'] = 'jpg';
$config['max_size'] = '100';
$config['max_width'] = '400';
$config['max_height'] = '400';
$this->load->library('upload',$config);
$data['query'] = $this->db->get('kategori');
if($this->form_validation->run() == FALSE && ! $this->upload->do_upload()) {
$data['error'] = $this->upload->display_errors();
$data['success'] = '';
$this->load->view('backoffice/tambahbarang',$data);
} else {
$upload_data = $this->upload->data();
$data['error'] = '';
$data = array(
'idkategori' => $this->input->post('idkategori'),
'namabarang' => $this->input->post('nbarang'),
'image' => $upload_data['file_name'],
'status' => 1
);
$data_insert = $this->db->insert('barang',$data);
if($data_insert == TRUE) {
$data['query'] = $this->db->get('kategori');
$query = $this->db->get('barang');
$rows = $query->row();
$data['idbarang'] = $rows->idbarang;
$harga = array(
'idbarang' => $data['idbarang'],
'satuan' => $this->input->post('stcbarang'),
'harga' => $this->input->post('hbarang')
);
$this->db->insert('hargabarang',$harga);
$data['success'] = '<b>Barang Telah Ditambahkan</b>';
$this->load->view('backoffice/tambahbarang',$data);
} else {
$data['success'] = '<b>Barang Gagal Ditambahkan</b>';
$this->load->view('backoffice/tambahbarang',$data);
}
}
}
This code success insert all of data to database, except on column 'image' that I fill with '$upload_data['file_name']' this empty on my database.
what's wrong with my code?
please help thanks
You can use this format:
/*
* ------- Start Image Upload---------
*/
$config['upload_path'] = 'image/product_images/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '100';
$config['max_width'] = '400';
$config['max_height'] = '400';
$this->load->library('upload', $config);
$this->upload->initialize($config);
$error='';
$fdata=array();
if ( ! $this->upload->do_upload('product_image'))
{
$error = $this->upload->display_errors();
echo $error;
exit();
}
else
{
$fdata = $this->upload->data();
$data['product_image']=$config['upload_path'] .$fdata['file_name'];
}
/*
* --------End Image Upload---------
*/
$this->super_admin_model->save_product_info($data);

Uploading an image in codeigniter

I am trying to upload an image,create thumbnail but i get an error.
Here is my controller.
<?php
class Upload extends Controller {
function Upload()
{
parent::Controller();
$this->load->helper(array('form','url','file'));
}
function index()
{
$this->load->view('upload_form'); //Upload Form
}
function picupload()
{
//Load Model
$this->load->model('Process_image');
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '2048'; //2 meg
$this->load->library('upload');
foreach($_FILES as $key => $value)
{
if( ! empty($key['name']))
{
$this->upload->initialize($config);
if ( ! $this->upload->do_upload($key))
{
$errors[] = $this->upload->display_errors();
}
else
{
$this->Process_image->process_pic();
}
}
}
$data['success'] = 'Thank You, Files Upladed!';
$this->load->view('upload_success', $data); //Picture Upload View
}
}
?>
My model:
<?php
class Process_image extends Model {
function Process_image()
{
parent::Model();
$this->load->library('image_lib');
//Generate random Activation code
function generate_code($length = 10){
if ($length <= 0)
{
return false;
}
$code = "";
$chars = "abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ123456789";
srand((double)microtime() * 1000000);
for ($i = 0; $i < $length; $i++)
{
$code = $code . substr($chars, rand() % strlen($chars), 1);
}
return $code;
}
}
function process_pic()
{
//Connect to database
$this->load->database();
//Get File Data Info
$uploads = array($this->upload->data());
$this->load->library('image_lib');
//Move Files To User Folder
foreach($uploads as $key[] => $value)
{
//Gen Random code for new file name
$randomcode = generate_code(12);
$newimagename = $randomcode.$value['file_ext'];
//Creat Thumbnail
$config['image_library'] = 'GD2';
$config['source_image'] = $value['full_path'];
$config['create_thumb'] = TRUE;
$config['thumb_marker'] = '_tn';
$config['master_dim'] = 'width';
$config['quality'] = 75;
$config['maintain_ratio'] = TRUE;
$config['width'] = 175;
$config['height'] = 175;
$config['new_image'] = '/pictures/'.$newimagename;
//$this->image_lib->clear();
$this->image_lib->initialize($config);
//$this->load->library('image_lib', $config);
$this->image_lib->resize();
//Move Uploaded Files with NEW Random name
rename($value['full_path'],'/pictures/'.$newimagename);
//Make Some Variables for Database
$imagename = $newimagename;
$thumbnail = $randomcode.'_tn'.$value['file_ext'];
$filesize = $value['file_size'];
$width = $value['image_width'];
$height = $value['image_height'];
$timestamp = time();
//Add Pic Info To Database
$this->db->set('imagename', $imagename);
$this->db->set('thumbnail', $thumbnail);
$this->db->set('filesize', $filesize);
$this->db->set('width', $width);
$this->db->set('height', $height);
$this->db->set('timestamp', $timestamp);
//Insert Info Into Database
$this->db->insert('pictures');
}
}
}
?>
The error:
A PHP Error was encountered
Severity: Warning
Message: rename(C:/wamp/www/uploads/Heaven_Clouds.jpg,/pictures/kFttl7lpE7Rk.jpg) [function.rename]: No such file or directory
Filename: models/Process_image.php
Line Number: 68
This is line 68:
rename($value['full_path'],'/pictures/'.$newimagename);
Remove the "/" before "picutres" in
rename($value['full_path'],'/pictures/'.$newimagename);
It wanna say that you want put your renamed file in a directory named "pictures" placed at the root of an Unix file system, then you're obviously in a Windows system and you do not seem to have a "pictures" directory at the root of your disk.
result :
rename($value['full_path'],'pictures/'.$newimagename);
This is a very simple script taken partly from the CI Docs:
$config['upload_path'] = 'uploads/cgm/';
$config['allowed_types'] = 'gif|jpg|png|bmp|jpeg';
$config['max_size'] = '0';
$config['max_width'] = '0';
$config['max_height'] = '0';
$this->load->library('upload', $config);
$configThumb = array();
$configThumb['image_library'] = 'gd2';
$configThumb['source_image'] = '';
$configThumb['create_thumb'] = TRUE;
$configThumb['maintain_ratio'] = TRUE;
$configThumb['width'] = 100;
$configThumb['height'] = 120;
$this->load->library('image_lib');
for($i = 1; $i < 6; $i++) {
$upload = $this->upload->do_upload('file'.$i);
if($upload === FALSE) continue;
$data = $this->upload->data();
$uploadedFiles[$i] = $data;
$imgName = $this->pictures_m->addPicture(array('listing_id' => $listing_id, 'ext' => $data['file_ext'], 'picture_name' => $this->input->post('file'.$i.'name')));
if($data['is_image'] == 1) {
$configThumb['source_image'] = $data['full_path'];
$configThumb['new_image'] = $data['file_path'].$imgName.$data['file_ext'];
$this->image_lib->initialize($configThumb);
$this->image_lib->resize();
}
rename($data['full_path'], $data['file_path'].$imgName.$data['file_ext']);
}
this will take 5 images, but if you only have one, you can just change the for loop.
i had the same problem but, in my scenario i've to only upload the array of files so i did some small changes to the library 'Upload.php'
view
<form encrypt="multipart/form-data" ...>
<input type="file" name="your_name[]" />
<input type="file" name="your_name[]" />
<input type="submit" />
</form>
controller
for($i = 0; $i < count($_FILES['your_name']['name']); $i++) {
$config['upload_path'] = 'your upload path';
$this->upload->initialize($config);
$this->upload->do_upload('listing_images', $i);
endfor;
if you have single file to upload then duplicate the function in system/libraries/Upload.php
function do_upload($field) to function do_upload_array($field, $i)
put [$i] index on lines 160, 162, 196, 197
and
function _file_mime_type($_FILES[$field]) to function _file_mime_type_array($_FILES[$field], $i)
and put [$i] index on lines 1026, 1043, 1057 and 1065
thats it...
your file array will upload easily now....

Resources