Codeignitor multiple input file upload from a dynamic form [duplicate] - php

This question already has answers here:
Multiple files upload in Codeigniter
(5 answers)
Closed 8 months ago.
I am having a dynamic form(drag and drop form) using Jquery which has multiple input type=file. So the name of the input type changes using a random number. Below is a sample code from view source:
<?php echo $error;?>
<?php echo form_open_multipart('upload/do_upload');?>
<form action="" enctype="multipart/form-data" method="post" accept-charset="utf-8">
<div id="sjfb-fields">
<div class="my-3 p-3 bg-white rounded box-shadow">
<div id="sjfb-399480" class="sjfb-field sjfb-images" style="min-height:100px;">
<label for="images-399480" style="color:grey;font-size:12px">Upload the screenshot</label>
<input type="file" name="img-399480" id="images-399480">
</div>
</div>
<div class="my-3 p-3 bg-white rounded box-shadow">
<div id="sjfb-857945" class="sjfb-field sjfb-images" style="min-height:100px;">
<label for="images-857945" style="color:grey;font-size:12px">Test Images</label>
<input type="file" name="img-857945" id="images-857945">
</div>
</div>
<div class="my-3 p-3 bg-white rounded box-shadow">
<div id="sjfb-792565" class="sjfb-field sjfb-images" style="min-height:100px;">
<label for="images-792565" style="color:grey;font-size:12px">More Images</label>
<input type="file" name="img-792565" id="images-792565">
</div>
</div>
</div>
<button type="submit" name="save" class="btn btn-primary">Save</button>
</form>
I have used below code in the controller for one image upload:
$config['upload_path'] = 'public/Uploads/Inspection/';
$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('userfile'))
{
$error = array('error' => $this->upload->display_errors());
}
else
{
$data = array('upload_data' => $this->upload->data());
}
I have tried the upload with one input type="file" and it works(used image's name userfile).
This form has multiple input type=file and I was wondering is there any way I can upload the files separately?
I am new to codeigniter as well
Thanks!

Check this out :
controller part :
$files = $_FILES; //getting the files from post
$cpt = count($_FILES['photo']['name']); //number of files uploaded
for($i=0;$i<$cpt;$i++){ // in loop to upload multiple files
$file_name=$_FILES['photo']['name'][$i];
if($i==0){ //name the file according to the number /name as u like
echo $i;
$name='_first';
}elseif($i==2){
$name='_second';
}else{
$name='_third';
}
//ci library to upload photos
$this->load->library('upload');
$_FILES['photo']['name']= $files['photo']['name'][$i];
$_FILES['photo']['type']= $files['photo']['type'][$i];
$_FILES['photo']['tmp_name']= $files['photo']['tmp_name'][$i];
$_FILES['photo']['error']= $files['photo']['error'][$i];
$_FILES['photo']['size']= $files['photo']['size'][$i];
$config = array(
'file_name' => $name,
'allowed_types' => 'jpg', //add option as u like
'max_size' => 3000,
'overwrite' => TRUE,
'upload_path'=>'./uploads/' //use your respective path to upload
);
$this->upload->initialize($config);
if (!$this->upload->do_upload('photo')) {
$data_error = array('msg' => $this->upload->display_errors());
} else {
$data = $this->upload->data();
}
}
And Form in html to upload Photos : input name changed to photo[] for all
<?php echo $error;?>
<?php echo form_open_multipart('upload/do_upload');?>
<form action="" enctype="multipart/form-data" method="post" accept-charset="utf-8">
<div id="sjfb-fields">
<div class="my-3 p-3 bg-white rounded box-shadow">
<div id="sjfb-399480" class="sjfb-field sjfb-images" style="min-height:100px;">
<label for="images-399480" style="color:grey;font-size:12px">Upload the screenshot</label>
<input type="file" name="photo[]" id="images-399480">
</div>
</div>
<div class="my-3 p-3 bg-white rounded box-shadow">
<div id="sjfb-857945" class="sjfb-field sjfb-images" style="min-height:100px;">
<label for="images-857945" style="color:grey;font-size:12px">Test Images</label>
<input type="file" name="photo[]" id="images-857945">
</div>
</div>
<div class="my-3 p-3 bg-white rounded box-shadow">
<div id="sjfb-792565" class="sjfb-field sjfb-images" style="min-height:100px;">
<label for="images-792565" style="color:grey;font-size:12px">More Images</label>
<input type="file" name="photo[]" id="images-792565">
</div>
</div>
</div>
<button type="submit" name="save" class="btn btn-primary">Save</button>
</form>
Working on my local
see this https://www.codeigniter.com/user_guide/libraries/file_uploading.html for config option

Related

file upload error messages are not displaying in codeigniter

I'm trying to insert data into database through a form. I'm uploading 2 image files, in database path of the files will be stored. I'm trying to do server side validation. when user does not upload a file or when user is uploading wrong file type, an error messages should display and page should return to same page with no data inserted into database.
This is my view:
<div class="main-panel">
<div class="content-wrapper">
<div class="row">
<div class="col-md-12 grid-margin stretch-card">
<div class="card">
<div class="card-body">
<h4 class="card-title">Add News & Event</h4>
<p class="card-description"> </p>
<?php echo validation_errors("<div class='alert alert-danger'>","</div>");?>
<?php if($failed = $this->session->flashdata('addNewsFailed')){
echo '<div class="alert alert-danger">' ;
echo $failed;
echo '</div>';
}?>
<form class="forms-sample" action="" method="post" enctype="multipart/form-data">
<div class="form-group">
<label for="exampleInputName1">Title</label>
<input type="text" class="form-control" id="exampleInputName1" value="<?php echo
set_value("title");?>" name="title">
</div>
<div class="form-group">
<label for="exampleInputName1">Sub Title</label>
<input type="text" class="form-control" id="exampleInputName1" value="<?php echo set_value("sub");?>" name="sub_title">
</div>
<div class="form-group">
<label for="exampleInputName1">Event Date</label>
<input type="text" class="form-control" id="exampleInputName1" name="date" value="<?php echo date('d - M - y ');//echo set_value("date");?>">
</div>
<div class="container">
<div class="row">
<div class="col-md">
<div class="form-group">
<label>Feature Image</label>
<div class="input-group col-xs-12">
<input type="file" class="form-control file-upload-info" placeholder="Upload Image" name="img" style="z-index: 9999; opacity: 0;" id="image">
<div id="imageName"></div>
<span class="input-group-append">
<button class="file-upload-browse btn btn-info" type="button" style="position: absolute; left: 0; padding: 6px 23px;border-radius:3px;">Upload</button> </span>
</div>
<?php if(isset($upload_error)){
echo $upload_error;
}?>
</div>
</div>
<div class="col-md">
<div class="form-group">
<label> Banner Image</label>
<div class="input-group col-xs-12">
<input type="file" class="form-control file-upload-info" placeholder="Upload Image" name="banner" id="banner" style="opacity: 0; z-index: 9999;">
<div id="bannerName"></div>
<span class="input-group-append">
<button class="file-upload-browse btn btn-info" type="button" style="position: absolute;left: 0;padding: 6px 23px;border-radius: 3px;">Upload</button></span>
</div>
<?php if(isset($upload_error1)){
echo $upload_error1;
}?>
</div>
</div>
</div>
</div>
<span class="input-group-append">-->
<div class="form-group">
<label for="exampleTextarea1">Text</label>
<textarea class="form-control" id="exampleTextarea1" rows="2" name="para" value=""><?php echo set_value("para");?></textarea>
</div>
<button type="submit" class="btn btn-success mr-2">Add</button>
<button class="btn btn-light">Cancel</button>
</form>
</div>
</div>
</div>
</div>
</div>
This is my controller:
public function addEvent()
{
//load library
$this->load->library('form_validation');
$this->load->helper('form');
//set rules for validation
$this->form_validation->set_rules("title", "Title", "required");
$this->form_validation->set_rules("date", "Event Date", "required");
$this->form_validation->set_rules("para", "Text", "required");
//template
$this->output->set_template('admin_layout');
//image upload
$config = [
'upload_path' => './uploads/',
'allowed_types' => 'gif|jpg|png',
];
$this->load->library('upload', $config);
//validation
if ($this->form_validation->run()) {
$post = $this->input->post();
if (!$this->upload->do_upload('img')) {
$upload_error = $this->upload->display_errors();
$this->load->view('dashboard/pages/forms/addEvent', compact('upload_error'));
} else {
$Feature1 = $this->upload->data();
$image_path = base_url('uploads/' . $Feature1['raw_name'] . $Feature1['file_ext']);
$post['image_path'] = $image_path;
}
if (!$this->upload->do_upload('banner')) {
$upload_error1 = $this->upload->display_errors();
$this->load->view('dashboard/pages/forms/addEvent', compact('upload_error1'));
} else {
$carsousel = $this->upload->data();
$banner = base_url('uploads/' . $carsousel['raw_name'] . $carsousel['file_ext']);
$post['banner'] = $banner;
}
$this->load->model('loginmodel', 'addNews');
$insert_id = $this->addNews->addNews($post);
if ($insert_id) {
$this->session->set_flashdata("addNewsSuccess", 'News & Event Added Successfully');
redirect('dashboard/update_news/' . $insert_id);
} else {
$this->session->set_flashdata("addNewsFailed", 'Failed');
$this->load->view('dashboard/pages/forms/addEvent');
}
} else {
$upload_error = $this->upload->display_errors();
$this->load->view('dashboard/pages/forms/addEvent', compact('upload_error'));
}
}
This is my model:
public function addNews($array)
{
$this->db->insert('news', $array);
return $this->db->insert_id();
}
My form validation are working perfectly but when user is uploading wrong file type or does not upload any file then file upload error message is not displaying and data is inserting into database the with both image field empty.

move_uploaded_file( ) not working on video/audio/pdf

I've done an upload page that should upload the files and set their name in the database. It works just perfect with the pictures , but the sound formats and the other ones doesn't seem to work.
This is how my html part look
<form method="post" enctype="multipart/form-data">
<div class="card card-login">
<?= FH::csrfInput() ?>
<div class="card-header text-center" data-background-color="rose" >
<h3 class="card-title">Upload</h3>
</div>
<div class="card-content">
<div class="input-group">
<span class="input-group-addon">
</span>
<div class="form-group label-floating">
<label class="control-label"><h4>Chose a name for the file</h4></label>
<br>
<input type="textd" name="name" id="name" class="form-control" value="">
</div>
<br><br>
<div class="form-group label-floating">
<label class="control-label"><h4>Choose a file</h4></label>
<br>
<input type="file" id="file" name="file" >
</div>
</div>
</div>
<div class="footer text-center">
<div class="file-upload">
<label for="submit" class="file-upload__label">
<div class="isa_error_class">
<?= FH::displayErrors($this->displayErrors)?>
</div>
<button class="btn btn-wd btn-lg" data-background-color="rose">Submit</button>
</label>
<input type="submit" name="submit" value="Submit" class="file-upload__input">
</div>
</div>
</form>
And there is the php part
if($this->request->isPost())
{
$this->request->csrfCheck();
$upload->assign($this->request->get());
$upload->user_id = Users::currentUser()->id;
$upload->name .= "." . pathinfo($_FILES['file']['name'] , PATHINFO_EXTENSION);
$value = pathinfo($_FILES['file']['name'] , PATHINFO_EXTENSION);
$upload->format = Upload::setFormat($value);
$dir = Users::currentUser()->id;
if(move_uploaded_file($_FILES["file"]["tmp_name"],'files' . DS . $dir . DS . $upload->name ))
{
if($upload->save())
{
Router::redirect('upload');
}
else
{
$upload->addErrorMessage('file','There were a problem saving in the database.');
}
}
else
{
$upload->addErrorMessage('file','There were a problem uploading it.');
}
}
The DS is the separator. The image formats seems to work perfect , but the other formats don't. Any ideas ?
You should check if u have allowed file_uploads = On in your php.ini and also check the maximum file size upload_max_filesize= 20M and to make sure that you are not passing it.

Upload image it's not working codeigniter

I have 2 websites in 1 htdocs directory. The structure's like this
The main directory it's structured like this(name:Quartiere):
Quartiere
_admin
application
assets
Second website directory it's _admin with the same structure(default CodeIgniter structure).
I'm trying to upload a file from _admin to the main directory assets folder, but for some reason, it's not working.I tried other answers from other post but nothing it helped.
What I tried:
Put 'userfile' in do_upload
Checked if the form it's multipart(it is)
What I checked:
If the path it's good(it is)
If the size of the photo it's smaller than 2048(it is)
_admin Controller:
public function add_product(){
if(!$this->session->userdata('logged_in')){
redirect('users/login');
}
$data['title'] = 'Adauga Produs';
$data['categories'] = $this->category_model->get_categories();
$this->form_validation->set_rules('name','Nume','required');
$this->form_validation->set_rules('category','Categorie','required');
$this->form_validation->set_rules('ingredients','Ingrediente');
$this->form_validation->set_rules('price','Pret','required');
$this->form_validation->set_rules('grams','Gramaj','required');
if($this->form_validation->run() === FALSE){
$this->load->view('templates/header');
$this->load->view('products/adauga', $data);
$this->load->view('templates/footer');
}else{
//upload image
$config['upload_path'] = 'http://localhost/quartiere/assets/images';
$config['allowed_types'] = 'jpg|png|jpeg';
$config['max_size'] = '2048';
$config['max_width'] = '2000';
$config['max_height'] = '2000';
$this->load->library('upload',$config);
if(!$this->upload->do_upload('userfile')){
$errors = array('error' => $this->upload->display_errors());
$food_image = 'noimage.png';
}else{
$data = array('upload_data' => $this->upload->data());
$food_image = $_FILES['userfile']['name'];
}
$this->food_model->add_product($food_image);
redirect('produse/adauga');
}
}
_admin View:
<?php echo validation_errors();?>
<?php echo form_open_multipart('products/add_product');?>
<div class="row">
<div class="col-md-4 col-md-offset-4">
<h1 class="text-center">
<?php echo $title; ?>
</h1>
<div class="form-group">
<input type="text" name="name" class="form-control" placeholder="Nume Produs" required/>
</div>
<div class="form-group">
<select class="form-control" name="category" required>
<?php foreach($categories as $category):?>
<option value="<?php echo $category['id'];?>"><?php echo $category['category_name'];?></option>
<?php endforeach;?>
</select>
</div>
<div class="form-group">
<label>Bar:</label><br>
Da <input type="radio" name="bar" class="from-control" value="1"/>
Nu <input type="radio" name="bar" class="from-control" value="0"/>
</div>
<div class="form-group">
<input type="text" name="ingredients" class="form-control" placeholder="Ingrediente"/>
</div>
<div class="form-group">
<input type="number" name="grams" class="form-control" placeholder="Gramaj"/>
</div>
<div class="form-group">
<label>Poza:</label>
<input type="file" name="userfile" size="10"/>
</div>
<div class="form-group">
<input type="number" name="price" class="form-control" placeholder="Pret" required/>
</div>
<button type="submit" class="btn btn-success btn-block">Adauga Produs</button>
</div>
</div>
<?php form_close(); ?>
You can make the upload path to - '../assets/images' - or - $_SERVER['DOCUMENT_ROOT'].'/quartiere/assets/images'. Either way is fine.

Upload multiples files with CodeIgniter

I'm trying to post two different types of files on two different fields into my database. I've been looking for the answer on the entire Stack Overvlow, but I still couldn't find it.
This is my controller:
public function insertLamaran()
{
$pas_foto = ($_FILES['pas_foto']['name']);
$cv = ($_FILES['cv']['name']);
if ($pas_foto !== "")
{
$config['upload_path'] = './uploads/';
$config['log_threshold'] = 1;
$config['allowed_types'] = 'jpg|png|jpeg|gif';
$config['max_size'] = '100000'; // 0 = no file size limit
$config['file_name']='smallImage.jpg';
$config['overwrite'] = false;
$this->load->library('upload', $config);
$this->upload->do_upload('pas_foto');
$upload_data = $this->upload->data();
$data['pas_foto'] = $upload_data['file_name'];
}
if ($cv !== "")
{
$config['file_name']='bigImage.pdf';
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'pdf';
$config['max_size'] = '100000'; // 0 = no file size limit
$config['overwrite'] = false;
$this->load->library('upload', $config);
$this->upload->do_upload('filename1');
$upload_data = $this->upload->data();
$data['cv'] = $upload_data['file_name'];
}
$data['u_id'] = $this->input->post('u_id');
$this->M_upload->insertLamaran($data);
}
and this is my view:
<form action="<?php echo base_url('Upload/insertLamaran')?>" method="post">
<input hidden type="text" name="u_id" value="<?php echo ucfirst($this->session->userdata('u_id')); ?>"></input><br>
<div class="row wowload fadeInLeftBig">
<div class="col-sm-6 col-sm-offset-3 col-xs-12">
<label for="pasfoto">Pas Foto (.jpg)</label>
<input id="pas_foto" type="file" name="pas_foto" multiple="true">
<label for="CV">CV (.pdf)</label>
<input id="cv" type="file" name="cv" multiple="true">
<button class="btn btn-primary"><i class="fa fa-paper-plane"></i> Send</button>
</div>
</div>
</form
the errors said that
Undefined index: pas_foto. Filename: controllers/Upload.php Line Number: 22
Does anybody know what's happening, and how I can fix it?
as i seen you correct form type so answer for pdf file
you forgot to add pdf file name
change this
$this->upload->do_upload('filename1');
into this
$this->upload->do_upload('cv');
First, load url helper in your controller's constructor. I think your view file must be like this.Need to put enctype="multipart/form-data" for file uploading.
<form action="<?php echo base_url('upload/insertLamaran');?>" method="post" enctype='multipart/form-data'>
<input hidden type="text" name="u_id" value="<?php echo ucfirst($this->session->userdata('u_id')); ?>"></input><br>
<div class="row wowload fadeInLeftBig">
<div class="col-sm-6 col-sm-offset-3 col-xs-12">
<label for="pasfoto">Pas Foto (.jpg)</label>
<input id="pas_foto" type="file" name="pas_foto" multiple="true">
<label for="CV">CV (.pdf)</label>
<input id="cv" type="file" name="cv" multiple="true">
<button class="btn btn-primary" type="submit"><i class="fa fa-paper-plane"></i> Send</button>
</div>
</div>
</form>

upload multiple image with different name using codeigniter

I am trying to upload the three images from html form,with three different names.But it shows error
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['file_name'] = $this->input->post('mobile_name').'_front.jpg';
$config['overwrite'] = TRUE;
$this->load->library('upload', $config);
if ($this->upload->do_upload('files'))
{
$_POST['mobile_img1']= $this->upload->data()['file_name'];
}
else
{
echo "image upload fails";
exit();
}
This my codeigniter code to upload one image.
I have three image input field in html code
<div class="row">
<div class="col-md-4 col-md-offset-4">
<div class="form-group">
<label class="control-label">Mobile Image Front</label>
<input type="file" name="mobile_img1" class="filestyle" data-placeholder="No file">
</div>
<div class="form-group">
<label class="control-label">Mobile Image Back</label>
<input type="file" name="mobile_img2" class="filestyle" data-placeholder="No file">
</div>
<div class="form-group">
<label class="control-label">Mobile Image Side</label>
<input type="file" name="mobile_img3" class="filestyle" data-placeholder="No file">
</div>
</div>
</div>
in this html field i need to upload the first input as mobilename_front.jpg , second as mobilename_back.jpg and third as mobilename_side.jpg and also i need to upload this names in db.Give some ideas to implement this,
View Files
<div class="row">
<div class="col-md-4 col-md-offset-4">
<form method="POST" action="<?php echo site_url('my-controller/file_upload');?>" enctype='multipart/form-data'>
<div class="form-group">
<label class="control-label">Mobile Image Front</label>
<input type="file" name="mobile_img[]" class="filestyle" data-placeholder="No file">
</div>
<div class="form-group">
<label class="control-label">Mobile Image Back</label>
<input type="file" name="mobile_img[]" class="filestyle" data-placeholder="No file">
</div>
<div class="form-group">
<label class="control-label">Mobile Image Side</label>
<input type="file" name="mobile_img[]" class="filestyle" data-placeholder="No file">
</div>
<input type="submit" value="upload"></form>
</div>
</div>
My controller:
<?php
class My_Controller extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->library('upload');
}
public function file_upload(){
$files = $_FILES;
$cpt = count($_FILES['mobile_img']['name']);
for($i=0; $i<$cpt; $i++)
{
$mobileView=(($i == 0)?"_front":(($i == 1)?"_back":"_side")); //Here i assign first image(i = 0) as _front, second image(i = 1) as _back,third image(i = 2) as _side
$_FILES['mobile_img']['name']= $files['mobile_img']['name'][$i].$mobileView.time();// time() for time in seconds becauze we may need if same name uploaded file name
$_FILES['mobile_img']['type']= $files['mobile_img']['type'][$i];
$_FILES['mobile_img']['tmp_name']= $files['mobile_img']['tmp_name'][$i];
$_FILES['mobile_img']['error']= $files['mobile_img']['error'][$i];
$_FILES['mobile_img']['size']= $files['mobile_img']['size'][$i];
$this->upload->initialize($this->set_upload_options());
$this->upload->do_upload();
$fileName = $_FILES['mobile_img']['name'];
$images[] = $fileName;
}
$fileName = implode(',',$images);
$this->my_model->upload_image($fileName);
}
private function set_upload_options()
{
// upload an image 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;
}
}
?>
My model Function:
<?php
class My_Model extends CI_Model {
public function upload_image($fileName)
{
if($filename!='' ){
$filename1 = explode(',',$filename);
foreach($filename1 as $file){
$file_data = array(
'name' => $file,
'datetime' => date('Y-m-d h:i:s')
);
$this->db->insert('uploaded_files', $file_data);
}
}
}
}
?>
<?php echo form_open('admin/product_insert');?>
<div class="row form-group">
<div class="col-lg-2">
Image 1
</div>
<div class="col-lg-5">
<input type="file" class="form-control" name="photo1" required>
</div>
</div>
<div class="row form-group">
<div class="col-lg-2">
Image 2
</div>
<div class="col-lg-5">
<input type="file" class="form-control" name="photo2" Required>
</div>
</div>
<div class="row form-group">
<div class="col-lg-2">
Image 3
</div>
<div class="col-lg-5">
<input type="file" class="form-control" name="photo3" Required>
</div>
</div>
<input type="submit">
public function product_insert(){
$pro=$this->input->post('productName');
for($i=0;$i<=3;$i++){
$config['upload_path'] = './images/';
$config['allowed_types'] = 'gif|jpg|png';
$config['file_name']=$pro.$i;
$this->load->library('upload',$config);
$this->upload->do_upload('photo'.$i);
$this->upload->initialize($config);
}

Categories