How to upload multiple files with multiple inputs in codeigniter - php

How to upload multiple files with multiple inputs in codeigniter. Below is my code. I want to add many files but with different inputs for files.
if(!empty($_FILES['countryfile']['name']))
{
$filesCount = count($_FILES['countryfile']['name']);
for($i = 0; $i < $filesCount; $i++)
{
$imgFile=$_FILES['countryfile']['name'][$i];
$tmp_dir=$_FILES['countryfile']['tmp_name'][$i];
$imgSize=$_FILES['countryfile']['size'][$i];
//$upload_dir='../uploads/dish_images';
$imgExt=strtolower(pathinfo($imgFile,PATHINFO_EXTENSION));
$valid_extensions = array('jpeg', 'jpg', 'png', 'gif','pdf');
$image=rand(1000,10000).".".$imgExt;
$config['upload_path'] = '../admin/upload_doc';
//$config['upload_path'] = 'http://teq-staging.com/maswad-phase2/admin/uploads/dish_images/';
$config['allowed_types'] = 'jpg|jpeg|png|gif|pdf';
$config['file_name'] = $_FILES['countryfile']['name'];
$upload_dir=$config['upload_path'];
//$config['file_name']=$image;
$upload_dir=$config['upload_path'];
$this->upload->initialize($config);
if($this->upload->do_upload('countryfile')){
$upload_data = $this->upload->data();
}
}

upload form.php
<?php echo form_open_multipart('upload'); ?>
<p>
<?php echo form_label('File 1', 'userfile') ?>
<?php echo form_upload('userfile') ?>
</p>
<p>
<?php echo form_label('File 2', 'userfile1') ?>
<?php echo form_upload('userfile1') ?>
</p>
<p><?php echo form_submit('submit', 'Upload them files!') ?></p>
<?php form_close() ?>
the controller
function index()
{
// Has the form been posted?
if (isset($_POST['submit']))
{
// Load the library - no config specified here
$this->load->library('upload');
// Check if there was a file uploaded - there are other ways to
// check this such as checking the 'error' for the file - if error
// is 0, you are good to code
if (!empty($_FILES['userfile']['name']))
{
// Specify configuration for File 1
$config['upload_path'] = 'uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '100';
$config['max_width'] = '1024';
$config['max_height'] = '768';
// Initialize config for File 1
$this->upload->initialize($config);
// Upload file 1
if ($this->upload->do_upload('userfile'))
{
$data = $this->upload->data();
}
else
{
echo $this->upload->display_errors();
}
}
// Do we have a second file?
if (!empty($_FILES['userfile1']['name']))
{
// Config for File 2 - can be completely different to file 1's config
// or if you want to stick with config for file 1, do nothing!
$config['upload_path'] = 'uploads/dir2/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '100';
$config['max_width'] = '1024';
$config['max_height'] = '768';
// Initialize the new config
$this->upload->initialize($config);
// Upload the second file
if ($this->upload->do_upload('userfile1'))
{
$data = $this->upload->data();
}
else
{
echo $this->upload->display_errors();
}
}
}
else
{
$this->load->view("upload_form");
}
}

Related

insert multiple images in database using codeigniter and filepond

Following is my controller In this I am using two if statements one for multiple images and another is for the featured image.. my images are uploaded in a folder very well but multiple names are not inserted in the database...Only one file name is inserted in the database...
public function uploadApi()
{
if (isset($_FILES['userfile'])) {
$config['upload_path'] = 'uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 200000;
$config['max_width'] = 2024;
$config['max_height'] = 1768;
$this->upload->initialize($config);
$this->load->library('upload', $config);
$this->upload->do_upload('userfile');
$data = array( $this->upload->data());
$this->m->update_post($data[0]['file_name']);
}
if(isset($_FILES['userfile1'])) {
$config['upload_path'] = 'uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 200000;
$config['max_width'] = 2024;
$config['max_height'] = 1768;
$this->upload->initialize($config);
$this->load->library('upload', $config);
$this->upload->do_upload('userfile1');
$data = array( $this->upload->data());
$this->m->update_feature($data[0]['file_name']);
}
}
This is a model ..
#-Update images Post-#
public function update_post($picture) {
$post = array(
'post_images'=>$picture,
);
$this->db
->where('post_status','draft')
->update('post',$post);
return true;
}
public function update_feature($picture) {
$post = array(
'post_featured_image'=>$picture,
);
$this->db
// ->set('post_created', 'NOW()', FALSE)
->where('post_status','draft')
->update('post',$post);
return true;
}
filepond plugin script
FilePond.registerPlugin(
FilePondPluginFileValidateSize,
FilePondPluginImageExifOrientation,
FilePondPluginImageCrop,
FilePondPluginImageResize,
FilePondPluginImagePreview,
FilePondPluginImageTransform
);
// Set default FilePond options
FilePond.setOptions({
// maximum allowed file size
maxFileSize: '50MB',
imagePreviewHeight: 100,
imagePreviewWidth: 200,
instantUpload: true,
// crop the image to a 1:1 ratio
imageCropAspectRatio: '1:1',
// upload to this server end point
server: {
url: '<?php echo base_url() ?>Admin/uploadApi',
}
});
var pond = FilePond.create(document.querySelector('input[name="userfile"]'));
var pond = FilePond.create(document.querySelector('input[name="userfile1"]'));
**This is a view ..**
<form method="post" enctype="multipart/form-data" class="toggle-disabled" action="<?php echo base_url() ?>Admin/update_post1" id='ritesh'>
<div class="col-md-6">
<div class="form-group">
<label>Upload images</label>
<input type="file"
class="filepond"
name="userfile"
multiple
data-max-file-size="5MB"
data-max-files="50" data-validation="required extension" />
</div>
<div class="form-group">
<label>Feature image</label>
<input type="file"
class="filepond"
name="userfile1"
data-max-file-size="5MB"
data-validation="required extension"
/>
</div>
</form>
For multiple image upload you should post images array like; imagename[]. Your current approach is not good.
You must try already posted answers:
Multiple image upload with CodeIgniter
Multiple image upload with Codeigniter saving only one file path to MySQL Database
https://www.codexworld.com/codeigniter-upload-multiple-files-images/
Please try to this in controller
function uploadApi() {
$image = $_FILES;
foreach ($image as $key => $img) {
if (!is_dir('./Uploads/')) {
mkdir('./Uploads/', 0777, TRUE);
}
if (!empty($img['name'])) {
$config['upload_path'] = './Uploads/Products/';
$config['allowed_types'] = '*';
$config['max_size'] = '100';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$config['overwrite'] = TRUE;
$config['file_name'] = date('U') . '_' . $img['name'];
$this->load->library('upload', $config);
$this->upload->initialize($config);
if (!$this->upload->do_upload($key)) {
$error = array('error' => $this->upload->display_errors());
print_r($error);
die;
} else {
if ($this->upload->do_upload($key)) {
$image_data = $this->upload->data();
$update["userfile"] = $config['file_name'];
$res = $this->m->update_post($update);
}
}
}
}
$this->load->view('imgtest');
}

how to reset method in codeigniter

I have a form that uploads many files and images at the same time.
the problem is this method
$this->upload->display_errors()
each time the loop goes through this method it saves error from the previous loop round
$error[$i]= "File error: ".$this->upload->display_errors();
for example, if I uploaded two illegal files it shows me this
index 0: file is not allowed
index 1: file is not allowed file is not allowed
So how can I reset this method?
ps: I tried to reset() function and it didn't work
UPDATE
This is the method
public function do_upload($product_id)
{
$error = array();
if(isset($_FILES['files']['name'])&&!empty($_FILES['files']['name'][0])):
for ($i=0; $i <count($_FILES['files']['name']) ; $i++) :
$config['upload_path'] = './images/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 1;
$this->load->library('upload', $config);
$_FILES['files[]']['name'] = $_FILES['files']['name'][$i];
$_FILES['files[]']['tmp_name'] = $_FILES['files']['tmp_name'][$i];
$_FILES['files[]']['size'] = $_FILES['files']['size'][$i];
if(!$this->upload->do_upload('files[]')){
$error[$i]= "File name: ". $_FILES['files']['name'][$i] ." ". $this->upload->display_errors() ."<br>";
}else{
$files = $this->upload->data();
$data = array('file_name'=>$files['file_name'],'product_id'=>$product_id,'file_type'=>$files['file_type']);
$this->Files_model->create_file($data);
}
endfor;
endif;
return $error;
//end method
}
We can't reset $this->upload->do_upload();
But we can reinitialize like that
// first upload
$this->config->load('upload');
-- Code to upload Here --
// Another file
$this->config->load('upload_other_files');
-- Code to upload Here --
OR You can defined multiple config array for each file Like below code :
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '100';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$this->load->library('upload', $config);
$this->upload->initialize($config);
For another files
$config2['upload_path'] = './uploads/';
$config2['allowed_types'] = 'gif|jpg|png';
$config2['max_size'] = '100';
$config2['max_width'] = '100';
$config2['max_height'] = '100';
$this->load->library('upload', $config2);
// Alternately you can set
$this->upload->initialize($config2);
You can reset (errors) like this:
$this->upload->error_msg = [];
...do_upload

files not uploading in codeigniter

I am trying to upload 2 files through a codeigniter controller. When i select the files and hit submit it always returns error. But when i do a var_dump($_FILES); it shows that the files are passing but not being captured by the codeigniter controller.
Can someone tell me what i am doing wrong? Below is my code
$config['upload_path'] = './docs/';
$config['allowed_types'] = 'jpg|doc|docx';
$config['max_size'] = 10000;
$config['max_width'] = 3000;
$config['max_height'] = 3000;
$this->load->library('upload', $config);
if ( !$this->upload->do_upload('userfile1') || !$this->upload->do_upload('userfile2'))
{
echo "error";
} else {
$f1= $this->upload->data('userfile1');
$f2= $this->upload->data('userfile2');
echo $f1['file_name'];
echo $f2['file_name'];
}
For multiple file uploading in CI please follow this way --
$config['upload_path'] = 'uploads/photos/';
$config['allowed_types'] = 'jpg|jpeg|png|gif';
$this->load->library('upload', $config);
for ($i=0; $i < count($_FILES['photos']['name']); $i++) {
$_FILES['photos[]']['name'] = $_FILES['photos']['name'][$i];
$_FILES['photos[]']['type'] = $_FILES['photos']['type'][$i];
$_FILES['photos[]']['tmp_name'] = $_FILES['photos']['tmp_name'][$i];
$_FILES['photos[]']['error'] = $_FILES['photos']['error'][$i];
$_FILES['photos[]']['size'] = $_FILES['photos']['size'][$i];
if ($this->upload->do_upload('photos[]')) {
$photos_files = array('upload_data' => $this->upload->data());
$photos_arr[] = $photos_files['upload_data']['file_name'];
}else{
$error[] = $this->upload->display_errors();
}
}

CodeIgniter Image Upload Function

How do I upload an image when I'm trying to save other data along with it? When the form submits, it hits the save function:
function save() {
$this->save_data($_POST, $_FILES);
}
function save_data($post_data, $file_data) {
// if theres an image
if(!empty($file_data['image']['size'])) {
$path = '/images';
$this->upload_image($path);
}
}
function upload_image($path) {
// CI is looking for $_FILES super global but I want to pass that data in
$config['upload_path'] = $path;
$config['allowed_types'] = 'jpg|png';
$config['max_size'] = '100';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$this->load->library('upload', $config);
$this->upload->data('image');
$this->upload->do_upload('image');
}
I can't figure out how to actually pass the file data to another function. All the examples I've seen shows the form submitting to a function that uploads the function right from it. I want to do the uploading from another function though.
if you are trying to check if file is actually beeing uploaded do following
//this is optional
if (empty($_FILES['userfile']['name'])) {
$this->form_validation->set_rules('userfile', 'picture', 'required');
}
if ($this->form_validation->run()) { //if using validation
//validated
if (!empty($_FILES['userfile']['name'])) {
//picture is beeing uploaded
$config['upload_path'] = './files/pcitures';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['encrypt_name'] = TRUE;
$this->load->library('upload', $config);
if (!$this->upload->do_upload('userfile')) {
//$error = array('error' => $this->upload->display_errors());
} else {
//no error, insert/update in DB
$tmp = $this->upload->data();
echo "<pre>";
var_dump($tmp);
echo "</pre>";
}
} else { ... }
}
My mistake was related to folder permissions.
For those of you that are looking to split the upload functionality into multiple functions:
Controller:
$save_data = $this->save_model->save_data($_POST, $_FILES);
Model:
function save_data($data, $file) {
// check if theres an image
if (!empty($file['image']['size'])) {
// where are you storing it
$path = './images';
// what are you naming it
$new_name = 'name_' . random_string('alnum', 16);
// start upload
$result = $this->upload_image($path, $new_name);
}
}
function upload_image($path, $new_name) {
// define parameters
$config['upload_path'] = $path;
$config['allowed_types'] = 'jpg|png';
$config['max_size'] = '1000';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$config['file_name'] = $new_name;
$this->load->library('upload', $config);
// upload the image
if ($this->upload->do_upload('image')) {
// success
// pass back $this->upload->data() for info
} else {
// failed
// pass back $this->upload->display_errors() for info
}
}

Codeigniter Upload multiple files different path to database

I have a problem with my multiple upload with codeigniter,
using image
another using pdf
When I uploaded the file uploaded twice and how to call different path to uploaded to database. this my code
Controller
public function upload(){
$catalog='catalog';
$userfile='userfile';
//for cover
$config['upload_path'] = './file/book/'; //Use relative or absolute path
$config['allowed_types'] = 'gif|jpg|png|';
$config['max_size'] = '100000';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$this->load->library('upload', $config);
$this->upload->initialize($config);
//$c=$this->upload->do_upload($userfile);
//for catalog
$config['upload_path'] = './file/book/pdf/'; //Use relative or absolute path
$config['allowed_types'] = 'pdf';
$config['max_size'] = '1000000';
$this->load->library('upload', $config);
$this->upload->initialize($config);
//$cat=$this->upload->do_upload($catalog);
if(!$this->upload->do_upload($catalog) && $this->upload->do_upload($userfile)){
$error = array('error' => $this->upload->display_errors());
$this->load->view('uploadds', $error);
}else{
$this->load->model("book_model");
$this->book_model->addnewbook();
redirect('book/book');
}
}
This model
function addnewbook(){
$fcat=array('upload_data' => $this->upload->data($userfile));
$fcatalog=array('upload_dataa' => $this->upload->data($catalog));
}
You need to handle multiple uploads independently. For this, you have to create separate custom objects for both uploads while loading the upload library. (See the code comments)
public function upload() {
// Cover upload
$config = array();
$config['upload_path'] = './file/book/';
$config['allowed_types'] = 'gif|jpg|png|';
$config['max_size'] = '100000';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$this->load->library('upload', $config, 'coverupload'); // Create custom object for cover upload
$this->coverupload->initialize($config);
$upload_cover = $this->coverupload->do_upload('cover');
// Catalog upload
$config = array();
$config['upload_path'] = './file/book/pdf/';
$config['allowed_types'] = 'pdf';
$config['max_size'] = '1000000';
$this->load->library('upload', $config, 'catalogupload'); // Create custom object for catalog upload
$this->catalogupload->initialize($config);
$upload_catalog = $this->catalogupload->do_upload('catalog');
// Check uploads success
if ($upload_cover && $upload_catalog) {
// Both Upload Success
// Data of your cover file
$cover_data = $this->coverupload->data();
print_r($cover_data);
// Data of your catalog file
$catlog_data = $this->catalogupload->data();
print_r($catlog_data);
} else {
// Error Occured in one of the uploads
echo 'Cover upload Error : ' . $this->coverupload->display_errors() . '<br/>';
echo 'Catlog upload Error : ' . $this->catalogupload->display_errors() . '<br/>';
}
}
Use the data on $cover_data['full_path'] and $catlog_data['full_path'] to update your database
$config['upload_path'] = 'frontend_assets/images/hospital';
$config['allowed_types'] = 'gif|jpg|png|jpeg|JPEG||JPG|PNG';
$this->load->library('upload', $config);
if($_FILES['logo']['name']){
$config['file_name'] = time() . $_FILES["logo"]['name'];
if (!$this->upload->do_upload('logo')) {
$this->upload->display_errors();
} else {
$upload = $this->upload->data();
$insert_data['logo'] = $config['upload_path'] . '/' . $upload['file_name'];
}
}
if($_FILES['bulding_photo']['name']){
$config['file_name'] = time() . $_FILES["bulding_photo"]['name'];
if (!$this->upload->do_upload('bulding_photo')) {
$this->upload->display_errors());
} else {
$upload = $this->upload->data();
$insert_data['bulding_photo'] = $config['upload_path'] . '/' . $upload['file_name'];
$this->image_size_fix($insert_data['bulding_photo'], $width = 200, $height = 200);
}
}

Categories