Upload multiples files with CodeIgniter - php

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>

Related

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

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

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 files with 2 seperate input fields

there is form the user enters the full name, age, profile pic, a document and submit. I managed to get the form working with one file upload but i cant find a proper way to upload files from 2 different inputs.
Below is my form
HTML
<form enctype="multipart/form-data" action="" method="post">
<div class="form-group">
<label>Name</label>
<input type="text" class="form-control" name="full_name"/>
</div>
<div class="form-group">
<label>Age</label>
<input type="text" class="form-control" name="age"/>
</div>
<div class="form-group">
<label>Choose Profile pic</label>
<input type="file" class="form-control" name="userfile1"/>
</div>
<div class="form-group">
<label>Choose Document</label>
<input type="file" class="form-control" name="userfile2"/>
</div>
<div class="form-group">
<input class="form-control" type="submit" name="upload" value="UPLOAD"/>
</div>
</form>
PHP
if ($this->input->post('upload'))
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png|doc|docx|pdf';
$config['max_size'] = 10000;
$config['max_width'] = 3000;
$config['max_height'] = 3000;
$this->load->library('upload', $config);
if ( !$this->upload->do_upload('userfile1'))
{
$this->session->set_flashdata('status','<div class="alert alert-danger alert-style-square">
<p style="text-align:center">There was an error. Try again. '.$this->upload->display_errors().'</p>
</div>');
}
else
{
$data = array('upload_data' => $this->upload->data());
$values = array('full_name'=>$this->input->post('full_name'),
'age'=>$this->input->post('age'),
'profile_image'=>$this->upload->data('file_name'),
//'document'=>$this->upload->data('file_name'),
'uploaded_date'=>date("Y-m-d H:i:s"));
var_dump($values);
}
}
Your help and guides will be highly appreciated
You could try changing
if ( !$this->upload->do_upload('userfile1'))
to
if ( !$this->upload->do_upload('userfile1') AND !$this->upload->do_upload('userfile2'))
Doing this will require the user to upload both images. If only one image is required you could try changing the AND to an OR.

Image Upload in CodeIgniter using PHP

I have a view where the user can edit his details.
View
<form class="form-horizontal" method ="post" action="<?php echo site_url('studentDashboardController/saveUserDetails');?>">
<?php echo form_open('studentDashboardController/saveUserDetails'); ?>
<?php echo $this->session->flashdata('msg'); ?>
<fieldset>
<!-- Form Name -->
<legend>User Details</legend>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="name">Full Name</label>
<div class="col-md-8">
<input id="name" name="name" type="text" class="form-control input-md" value="<?php foreach($details as $detail){?><?php echo $detail->name?><?php }?>">
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="dob">Date of Birth</label>
<div class="col-md-8">
<input id="dob" name="dob" type="text" placeholder="" class="form-control input-md" value="">
</div>
</div>
...
<!-- File Button -->
<div class="form-group">
<label class="col-md-4 control-label" for="userfile">Upload Profile Picture</label>
<div class="col-md-4">
<input id="userfile" name="userfile" class="input-file" type="file">
</div>
</div>
<!-- Button -->
<div class="form-group">
<label class="col-md-4 control-label" for="submit"></label>
<div class="col-md-4">
<button id="submit" name="submit" type="submit" class="btn btn-primary">Save Changes</button>
</div>
</div>
Controller
public function saveUserDetails()
{
if (isset($this->session->userdata['logged_in']))
{
$uid = ($this->session->userdata['logged_in']['userId']);
$data['notifyCount']= $this->notifications->getUnreadNotification($uid);
$data['title']= $this->notifications->getUnreadNotificationTitle($uid);
$data['notifyCount']= $this->notifications->getUnreadNotification($uid);
$data['users'] = $this->user->getUserNames();
$config['upload_path'] = './assets/img/taro/profilePictures/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '10000';
$config['max_width'] = '5000';
$config['max_height'] = '3000';
$this->load->library('upload', $config);
$this->upload->do_upload();
$upload_data = $this->upload->data();
$msg = $this->studentprofileModel->saveUserDetails($uid,$this->input->post());
$msgText = $msg['msg'];
$msgType = $msg['type'];
//Loading View
if($msgType == "danger")
{
$this->session->set_flashdata('msg', '<div class="alert alert-danger text-center">'.$msgText.'</div>');
}
else
{
$this->session->set_flashdata('msg', '<div class="alert alert-success text-center">'.$msgText.'</div>');
}
redirect(base_url('index.php/studentDashboardController/loadGeneralProfilePage'));
}
else
{
$this->load->view('login/loginView');
}
}
What I need to do is to first save the user details collected via the form by calling the studentprofileModel's saveUserDetails method. In this method I need to send the uploaded image's name so that I can store the image path in the db table's image field. And I need to upload the image to the assets folder's subdirectory taro as well.
I have done the following and the data from the form fields get updated in the DB. But the image file is not uploaded.
Any suggestions in this regard will be highly appreciated
You can add this code in your controller "function saveUserDetails()"
public function saveUserDetails()
{
if (isset($this->session->userdata['logged_in']))
{
$uid = ($this->session->userdata['logged_in']['userId']);
$post_data = $this->input->post();
if($_FILES['image']['name'])
{
//load upload library
$this->load->library('upload');
// Specify configuration for File
$config['upload_path'] = './assets/img/taro/profilePictures/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '10000';
$config['max_width'] = '5000';
$config['max_height'] = '3000';
$this->upload->initialize($config);
if ($this->upload->do_upload('image')){
$image_data = $this->upload->data();
$post_data['image'] = $image_data['file_name'];
}
else{
$error = $this->upload->display_errors();
}
}
$msg = $this->studentprofileModel->saveUserDetails($uid,$post_data);
$msgText = $msg['msg'];
$msgType = $msg['type'];
.....
}
Don't forget give permision to image folder.
I hope it will work for you!!
My first guess, before further tests, would be to add the enctype="multipart/form-data" attribute to your <form> tag, as it specifies how the form-data should be encoded when submitting it to the server and the multipart/form-data is required when the form includes any <input type="file">.
You can read more about this here.
Update 2:
Actually, it seems you may have two form tags opened? one from <form> and another one from form_open() function CI provides?
If so, use only one of them.
If you choose to do in HTML:
<form class="form-horizontal" method ="post" action="<?php echo site_url('studentDashboardController/saveUserDetails');?>" enctype="multipart/form-data">
If you choose to use CI's functions, there's two ways: form_open and form_open_multipart (which is exactly like form_open but it adds automatically the multipart thing)
form_open('studentDashboardController/saveUserDetails', array('enctype' => "multipart/form-data"))
or
form_open_multipart('studentDashboardController/saveUserDetails')
Update 3:
Make sure that the folder where the image will be uploaded to have enough permissions;
Pass the absolute path in here $config['upload_path'] = './assets/img/taro/profilePictures/' instead of the relative one
Also, change this $this->upload->do_upload(); to $this->upload->do_upload('userfile');
Let us know the results :)

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