i have a working multiple upload (document and image) CODEIGNITER - 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);
}

Related

Update Selected file on Multiple Upload 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 !

Redirect stopping multiple file upload CodeIgniter 3.0.4

I am trying to use redirect on my filemanager controller on my upload function when the form is success full.
How ever when I have the redirect('filemanager') on my success part of form it stops multiple files from being uploaded and then only uploads one.
But when I comment it out like so // redirect('filemanager') I can
upload multiple images fine.
Question: How can I still use my redirect on success form but make sure it uploads the multiple images that is selected rather than just one.
Controller
<?php
class Filemanager extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->library('upload');
}
public function index() {
$data['title'] = 'File Manager';
$data['template'] = 'template/common/filemanager_view';
$this->load->view('template/common/template_view', $data);
}
public function upload() {
$files = $_FILES;
if ($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];
$url = '';
$directory = $this->input->get('directory');
if (isset($directory)) {
$url .= $directory . '/';
} else {
$url .= '';
}
$config['upload_path'] = FCPATH . 'images/catalog/' . $url;
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 5000;
$config['max_width'] = 0;
$config['max_height'] = 0;
$config['overwrite'] = TRUE;
$this->upload->initialize($config);
if (!$this->upload->do_upload()) {
// reminder todo some error code here
} else {
redirect('filemanager');
}
}
}
}
}
I have got it working now thanks to #Vinie suggestion
<?php
class Filemanager extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->library('upload');
}
public function index($results = NULL) {
$data['title'] = 'File Manager';
$data['upload_data'] = array();
if ($results) {
foreach ($results as $result) {
$data['upload_data'][] = array(
'file_name' => $result['file_name']
);
}
}
$upload_errors = $this->upload->display_errors();
if (isset($upload_errors)) {
$data['upload_errors'] = $upload_errors;
} else {
$data['upload_errors'] = '';
}
$data['template'] = 'template/common/upload_view';
$this->load->view('template/common/template_view', $data);
}
public function upload() {
$files = $_FILES;
if ($files) {
$check_if_any_error = 0;
$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];
$url = '';
$directory = $this->input->get('directory');
if (isset($directory)) {
$url .= $directory . '/';
} else {
$url .= '';
}
$config['upload_path'] = FCPATH . 'images/catalog/' . $url;
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 5000;
$config['max_width'] = 0;
$config['max_height'] = 0;
$config['overwrite'] = TRUE;
$this->upload->initialize($config);
if (!$this->upload->do_upload()) {
$check_if_any_error++;
} else {
$results[] = $this->upload->data();
}
}
if($check_if_any_error > 0 ) {
$this->index();
} else {
$this->index($results);
}
} else {
redirect('filemanager');
}
}
}

How to get the name of userfiles in controller to add to database

This is the code so far.
I have 2 images that are getting uploaded and added to the desired map.
My question is, how do i get both names from the images so I can add just the names to the database together with my other form information.
public function CreateTypesForGamma() {
$type = new stdClass();
$type->TypeID = $this->input->post('typeID') == 0 ? null : $this->input->post('typeID');
$type->Titel = $this->input->post('titel');
$type->TechnischeFiche = $this->input->post('technischeFiche');
$type->GammaID = $this->input->post('gammaID');
$type->ExtLink = $this->input->post('extLink');
$type->InfoNL = $this->input->post('infoNL');
$type->InfoFR = $this->input->post('infoFR');
$type->InfoEN = $this->input->post('infoEN');
$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();
$fileName = $_FILES['userfile']['name'];
if ($i == 0)
$images[] = $fileName;
}
$fileName = implode(',',$images);
$this->gamma_model->upload_image($fileName);
system.out.println($images);
if ($type->TypeID == 0) {
$type->TypeID = $this->type_model->insert($type);
} else {
$this->type_model->update($type);
}
redirect('gamma/viewAdminGamma');
}
private function set_upload_options()
{
// upload an image options
$config = array();
$config['upload_path'] = APPPATH . 'images/types'; //give the path to upload the image in folder
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '5120';
$config['overwrite'] = FALSE;
return $config;
}
Change the code to following
$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();
$fileName = $_FILES['userfile']['name'];
$images[] = $fileName;
$type->TypeFoto=$fileName[0];// this gives name of first
image
$type->Lastentabel =$fileName[1];
}
$fileName = implode(',',$images);
$this->gamma_model->upload_image($fileName);
system.out.println($images);
if ($type->TypeID == 0) {
$type->TypeID = $this->type_model->insert($type);
} else {
$this->type_model->update($type);
}
redirect('gamma/viewAdminGamma');
}
private function set_upload_options()
{
// upload an image options
$config = array();
$config['upload_path'] = APPPATH . 'images/types'; //give the path to upload the image in folder
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '5120';
$config['overwrite'] = FALSE;
return $config;
}

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/

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