Update Selected file on Multiple Upload CodeIgniter - codeigniter

I've write the codeigniter for three upload file. And when i update one or two, the third will be overwrite data that i've upload before with blank in db. how to make it update only the file that i need to . i've try if !empty $_FILES but my head start smoky :(
<input type="file" class="form-control" name="userfile[]">Front
<input type="file" class="form-control" name="userfile[]">Back
<input type="file" class="form-control" name="userfile[]">Side
this my controller
public function prosesUpdate2(){
$data = $this->input->post('id');
$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();
$dataInfo[] = $this->upload->data();
}
$files = array(
'front' => $dataInfo[0]['file_name'],
'back' => $dataInfo[1]['file_name'],
'side' => $dataInfo[2]['file_name']
// 'userdatecreate' => date('Y-m-d H:i:s')
);
$result_set = $this->update_building->db_update($files, $data);
$this->session->set_flashdata('file_success', 'Upload File Success!');
}
the model
public function db_update($data,$id)
{
$this->db->where('id', $id);
$this->db->update('allbuidingdata', $data);
}

Please check the posted files before the update.
Slightly modify your code.
public function prosesUpdate2(){
$data = $this->input->post('id');
$this->load->library('upload');
$dataInfo = array();
$files = $_FILES;
$files_to_update = array();
$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();
$dataInfo[] = $this->upload->data();
}
$files_to_update= array(
'userdatecreate' => date('Y-m-d H:i:s')
);
if($dataInfo[0]['file_name']){
$files_to_update['front'] = $dataInfo[0]['file_name'];
}
if($dataInfo[1]['file_name']){
$files_to_update['back'] = $dataInfo[1]['file_name'];
}
if($dataInfo[2]['file_name']){
$files_to_update['side'] = $dataInfo[2]['file_name'];
}
$result_set = $this->update_building->db_update($files_to_update, $data);
$this->session->set_flashdata('file_success', 'Upload File Success!');
}

You forgot to place the field name in do_upload function
$this->upload->do_upload('userfile');
Hope this helps !

Related

Codeigniter: resizing multiple uploaded images gets only one image resized

I'm trying to resize all uploaded images uploaded from a form and save a resized copy in another folder. This method works fine with a single image upload not in a multiple image upload. The issue here that I get only 1 image resized. Here's the upload and resize code:
$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];
$config = array();
$config['upload_path'] = realpath(APPPATH . '../images/myfolder/');
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '2000';
$config['overwrite'] = FALSE;
$rand_string = $this->generateRandomString(3);
$ext = strtolower(pathinfo($_FILES['userfile']['name'], PATHINFO_EXTENSION));
$filename = round(microtime(true) * 1000).$rand_string.'.'.$ext;
$config['file_name'] = $filename;
$this->upload->initialize($config);
if ($this->upload->do_upload('userfile')) {
$this->resizeImage($filename);
$dataInfo[] = $this->upload->data();
}
}
Resizing function
public function resizeImage($filename)
{
$source_path = realpath(APPPATH . '../images/myfolder/'.$filename) ;
$target_path = realpath(APPPATH . '../images/myfolder/thumbs/') ;
$config_manip = array(
'image_library' => 'gd2',
'source_image' => $source_path,
'new_image' => $target_path,
'maintain_ratio' => TRUE,
'create_thumb' => TRUE,
'thumb_marker' => '',
'width' => 200,
'height' => 200
);
$this->load->library('image_lib', $config_manip);
if (!$this->image_lib->resize()) {
echo $this->image_lib->display_errors();
exit;
}
$this->image_lib->clear();
}
But I get just 1 image resize though all images are uploaded not just one. Why is this happening and how to fix i?
Assuming that all your images are getting uploaded (that is the case right?) then I would suggest trying: $this->upload->initialize($config, true); and:
$this->load->library('image_lib');
$this->image_lib->initialize($config_manip);
if (!$this->image_lib->resize()) {
echo $this->image_lib->display_errors();
exit;
}

uploading multiple image in codeigniter using same input

views
<form action="" method="POST" enctype="multipart/form-data">
<input type="file" name="userfile[]" size="40" multiple/>
<input type="submit" name="submit" value="Upload">
</form>
controller
public function image()
{
$data['error'] = '';
$this->load->model('StackM');
if(isset($_POST['submit']))
{
$data['update_pass_error_msg'] = $this->StackM->add_multiple_image();
}
$this->load->view('stack_view');
}
Model
public function add_multiple_image(){
if((!empty($_FILES['f2']['name'])))
{
$config['upload_path'] = 'uploads/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$files = $_FILES;
if ($files['f2']['name'][0] == '' )
{
# code...
return "Select a file to upload";
}
else
{
$mum_files = count($files['f2']);
for($i=0; $i<$mum_files; $i++)
{
if ( isset($files['f2']['name'][$i]) )
{
$config['file_name'] = time().'-'.$files['f2']['name'][$i];
$this->load->library('upload', $config);
$_FILES['f2']['name']= $files['f2']['name']["$i"];
$_FILES['f2']['type']= $files['f2']['type']["$i"];
$_FILES['f2']['tmp_name']= $files['f2']['tmp_name']["$i"];
$_FILES['f2']['error']= $files['f2']['error']["$i"];
$_FILES['f2']['size']= $files['f2']['size']["$i"];
$filename = rand().'-'.$_FILES['f2']['name'];
if (!empty($this->upload->do_upload('f2')))
{
$dataInfo[] = $this->upload->data();
$all_imgs = '';
if ( count($dataInfo) > 0) {
# code...
foreach ($dataInfo as $info) {
# code...
$all_imgs .= $info['file_name'];
$all_imgs .= ',';
}
}
}
}
}
}
}
else{
$all_imgs = "";
}
}
}
else{
$all_imgs = $this->session->userdata('image');
}
$this->db->insert('table_name', $all_imgs);
The problem I am facing in this code is Think suppose if I am adding 7 images, but it's showing only 5 images in database it's not taking more then five and also I want to know while editing the form if I don't want to change the image then it should remain same image so i have stored the old image in session and checking if it is empty then only it should session variable .
But In my code if I will not upload new one If I keep old image as then it will save blank
To avoid the offset error, inside of for loop you need to check if that array index is set or not:
Here I have a demo code to upload multiple files in CodeIgniter:
views/stack_view.php
<?php if ($this->session->flashdata('status')) { ?>
<h5><?=$this->session->flashdata('status')?>: <?=$this->session->flashdata('message')?></h5>
<?php } ?>
<?=form_open_multipart('stack', array('id' => 'my_id'))?>
<input type="file" name="userfile[]" size="40" multiple/>
<input type="submit" name="submit" value="Upload">
<?=form_close()?>
controllers/Stack.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Stack extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->library('session');
$this->load->helper(array('form', 'url'));
}
public function index()
{
if ($this->input->post('submit')) {
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$files = $_FILES;
if ($files['userfile']['name'][0] == '' ) {
# code...
$this->session->set_flashdata('status', 'error');
$this->session->set_flashdata('message', "Select a file to upload");
}
else
{
$mum_files = count($files['userfile']);
$dataInfo = array();
for($i=0; $i<$mum_files; $i++)
{
if ( isset($files['userfile']['name'][$i]) ) {
$config['file_name'] = time().'-'.$files['userfile']['name'][$i];
$this->load->library('upload', $config);
$_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"];
$filename = rand().'-'.$_FILES['userfile']['name'];
if ( ! $this->upload->do_upload('userfile'))
{
$error_message = $this->upload->display_errors();
$this->session->set_flashdata('status', 'error');
$this->session->set_flashdata('message', "$error_message");
}
else
{
//$data = array('upload_data' => $this->upload->data());
$this->session->set_flashdata('status', 'success');
$this->session->set_flashdata('message', "Files upload is success");
}
$dataInfo[] = $this->upload->data(); //all the info about the uploaded files are stored in this array
}
}
//here you can insert all the info about uploaded file into database using $dataInfo
$all_imgs = '';
if ( count($dataInfo) > 0) {
# code...
foreach ($dataInfo as $info) {
# code...
$all_imgs .= $info['file_name'];
$all_imgs .= ',';
}
}
$insert_data = array(
'your_column_name' => rtrim($all_imgs,",")
);
$this->db->insert('your_table_name', $insert_data);
}
}
$this->load->view('stack_view');
}
}
Try this script and I hope you will get some help from this.
This is working script try to upload it
public function upload()
{
$this->load->library('session');
if ( ! empty($_FILES))
{
$config['upload_path'] = "assets/uploads/";
$config['allowed_types'] = 'jpg|png|jpeg';
$config['max_size'] = 5120; //limit only 5 Mb
$this->load->library('upload');
$files = $_FILES;;
$number_of_files = count($_FILES['files']['name']);
$errors = 0;
$myname = $this->input->post('ad_title');
for ($i = 0; $i < $number_of_files; $i++)
{
//$randVal = rand(450,4550).time('d-y-m');
$filename = basename($files['files']['name'][$i]);
$extension = pathinfo($filename, PATHINFO_EXTENSION);
$new = md5($filename.''.time('d-y-m')).'.'.$extension;
$_FILES['files']['name'] = $new; //$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];
$image = array('upload_data' => $this->upload->data());
$image_name = $_FILES['files']['name'];
$ip = $this->input->ip_address();
$this->session->set_userdata("userIP",$ip);
//$this->session->unset_userdata("userIP");
$Dval = array(
"filename" => $image_name,
"ip" => $this->input->ip_address()
);
$this->member_model->tmp_image($Dval);
$this->upload->initialize($config);
if ( $this->upload->do_upload("files"))
{
$errors++;
$data = $this->upload->data();
echo json_encode($data['file_name']);
//code is for thumbnail and watermark on images
//$this->watermark($data['full_path']);
//$myPathfT = $config1['upload_path'] = "./assets/thumbs/".$aDir;
//mkdir($myPathfT);b
$config1 = array();
$config1['image_library'] = 'gd2';
$config1['source_image'] = $data['full_path'];
$config1['new_image'] = 'assets/uploads/thumbs/';
$config1['create_thumb'] = false;
$config1['quality'] = 50;
$config1['height'] = 150;
$config1['width'] = 150;
$this->load->library('image_lib',$config1);
$this->image_lib->initialize($config1);
$this->image_lib->resize();
$this->image_lib->clear();
}
}
if ($errors > 0)
{
//echo "Data Transferred";
}
}
elseif ($this->input->post('file_to_remove'))
{
$aDir = $this->session->userdata('Dir');
$file_to_remove = $this->input->post('file_to_remove');
unlink("./assets/mainFilesData/$aDir/" . $file_to_remove);
$array = $this->session->userdata('photo');
$dataF = array_diff($array, array($file_to_remove));
$this->session->set_userdata('photo',$dataF);
}
else
{
$this->listFiles();
}
}

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

Display all subfolders of folder in CodeIgniter

I am trying to display my uploaded content in my view page.
I have uploaded some files to my assets folder. In this the applicant (here) has an id, and uploading documents also have an id. During uploading these document ids are inserted in db with commas.
The uploaded path is ./assets/uploads/applicant_id/document_id.
I want to display the all files from this path. Problem is that when l have uploaded a document, and display only its (last uploaded) document files .
function index()
{
$application_id=$this->session->userdata('application_id');
$this->load->helper('directory');
$document_details = $this->home_model->get_document_details();
$$document_ids = $this->home_model->get_evidence_ids($application_id);
$$document_id= $evidence_ids->applicant_evidence_id;
$document= explode(',',$evidence_id);
for($i=0; $i < count($evidence); $i++)
{
$uploaded_files = array();
$uploaded_files = directory_map('./application/assets/uploads/'.$application_id.'/'.$document_id[$i]);
}
$data=array(
'document'=>$document,
'document_details'=>$document_details,
'page_name'=>'Home',
'dashboard_index'=>1,
'uploaded_files' =>$uploaded_files,
'application_id'=>$application_id,
'head_extra'=>'<link rel="stylesheet" type="text/css" href="'.base_url().'application/assets/css/home.css"> ',
'footer_extra'=>'',
);
$this->load->view('header',$data);
$this->load->view('index',$data);
$this->load->view('footer',$data);
}
function do_upload()
{
$evidence_id = $_POST['document_id'];
$application_id=$this->session->userdata('application_id');
$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($document_id,$application_id));
$this->upload->do_upload();
}
$evidence = $this->home_model->insert_evidence($application_id,$document_id);
$success_message = "Document Uploaded.";
$this->session->set_flashdata('success_message',$success_message);
redirect(base_url().'home','refresh');
}
private function set_upload_options($document_id,$application_id)
{
if(!is_dir('./application/assets/uploads/'.$application_id.'/'.$document_id))
{
mkdir('./application/assets/uploads/'.$application_id.'/'.$document_id, 0777, TRUE);
}
$config = array();
$config['upload_path'] = './application/assets/uploads/'.$application_id.'/'.$document_id;
$config['allowed_types'] = 'jpg|png|bmp|jpeg|gif|vnd.ms-excel|vnd.openxmlformats-officedocument.spreadsheetml.sheet|csv|pdf';
$config['max_size'] = '0';
$config['overwrite'] = FALSE;
return $config;
}
view
<div class="portal-body">
<?php $file_count = count($uploaded_files);
for($i=0;$i<$file_count;$i++)
{ ?>
<p><?php echo $uploaded_files[$i]; ?></p>
<?php } ?>
</div>
First get the images from database
For ex.
$images = image1,image2,image3;
$newImages = explode(',',$images);
Now use foreach loop
foreach($newImages as $img)
{
//check for file type
$name = $img;
$info = new SplFileInfo($name);
$extension = $info->getExtension();
//echo $extension;
if($extension == "jpg" || $extension == "png" || $extension == "gif" || $extension == "jpeg") {
<img src="<?php echo base_url('your file location/.$img');?>">;
}else{
show your file here
}
}
For more read this tutorial
http://w3code.in/2015/09/upload-file-using-codeigniter/

i have a working multiple upload (document and image) CODEIGNITER

I have made a working multiple upload in codeigniter but I'm having a problem on how am I gonna insert the file names of those files on two tables (documents and images table) which these two tables have two the same column name (ID, name). is there way that i could disjunct or compart my code for uploading image and doc. because I united them in one function.
here is my CODE. it is working.
VIEW
<?php echo form_open_multipart('test'); ?>
<label>Images</label>
<input type='file' multiple='multiple' name='userfile[]'>
<label>Documents</label>
<input type='file' multiple='multiple' name='userfile[]'>
<?php echo form_submit('submit', 'Upload them files!') ?>
CONTROLLER
function index()
{
if (isset($_POST['submit']))
{
$this->load->library('upload');
//$this->uploadfile($_FILES['userfile']);
$files = $_FILES;
$cpt = count($_FILES['userfile']['name']);
for($i=0; $i<$cpt; $i++)
{
$filename = $_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();
$this->upload->data();
}
}
$this->load->view("test");
}
private function set_upload_options()
{
// upload an image and document options
$config = array();
$config['upload_path'] = './upload_documents/';
$config['allowed_types'] = 'jpg|png|gif|jpeg|JPG|PNG|GIF|JPEG|pdf|doc|docx|xls|xlsx';
$config['max_size'] = '0'; // 0 = no file size limit
$config['max_width'] = '0';
$config['max_height'] = '0';
$config['overwrite'] = TRUE;
return $config;
}
These codes are working and it is able to transfer all the files on my desired path.
but I was wondering on making the MODEL, how am I gonna identify the file type as you seen my codes above I passed the name of the file on a variable "$filename". If you use print_r($filename), you'll see all the file name and it's file extension. Those names is the one that I will insert to my two tables accordingly to their type of file.
Is there any code for CodeIgniter or PHP code that I will use to identify the file type and pass it to the model with two function like upload_image or upload_docu? Help please.
so here it is..
CONTROLLER
function index()
{
if (isset($_POST['submit']))
{
$this->load->library('upload');
//$this->uploadfile($_FILES['userfile']);
$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();
$this->upload->data();
$ext = pathinfo($filename, PATHINFO_EXTENSION);
$img_ext_chk = array('jpg','png','gif','jpeg','JPG','PNG', 'GIF', 'JPEG');
if (in_array($ext,$img_ext_chk))
{
$this->asset->add_image($filename);
}
else
{
$this->asset->add_document($filename);
}
}
}
}
and to your MODEL
public function add_image($filename)
{
$data = array ('images' => $filename);
$this->db->insert('asset_images', $data);
}
public function add_document($filename)
{
$data = array ('documents' => $filename);
$this->db->insert('asset_documents', $data);
}

Resources