Good day Everyone who had an idea on multiple file upload. i want to achieved on how to send multiple file to be inserted in my datatables.
this my view page
<div class="form-group">
<input type="file" name="file">
<button type="submit" class="btn btn-success">Add New Record</button>
</div>`enter code here`
this is my function that will upload in the database
$path = './files';
$ckdir = is_dir($path);
if(!$ckdir){
mkdir($path, 0777, true);
}
$userid = $this->session->userdata("sessionid");
$filename =$path."/".$userid."-".$_FILES["file"]["name"];
if(!file_exists($filename."pdf")){
move_uploaded_file($_FILES["file"]["tmp_name"], $filename);
}
else{
return false;
}
View File:
<div class="form-group">
<input type="file" name="file[]">
<button type="submit" class="btn btn-success">Add New Record</button>
</div>
Controller File:
$path = './files';
$ckdir = is_dir ( $path );
if (! $ckdir) {
mkdir ( $path, 0777, true );
}
$countfiles = count ( $_FILES ['files'] ['name'] );
// Looping all files
for($i = 0; $i < $countfiles; $i ++) {
if (! empty ( $_FILES ['files'] ['name'] [$i] )) {
// Define new $_FILES array - $_FILES['file']
$_FILES ['file'] ['name'] = $_FILES ['files'] ['name'] [$i];
$_FILES ['file'] ['type'] = $_FILES ['files'] ['type'] [$i];
$_FILES ['file'] ['tmp_name'] = $_FILES ['files'] ['tmp_name'] [$i];
$_FILES ['file'] ['error'] = $_FILES ['files'] ['error'] [$i];
$_FILES ['file'] ['size'] = $_FILES ['files'] ['size'] [$i];
// Set preference
$config ['upload_path'] = $path;
$config ['allowed_types'] = '*';
$config ['file_name'] = $_FILES ['files'] ['name'] [$i];
// Load upload library
$this->load->library ( 'upload', $config );
// File upload
if ($this->upload->do_upload ( 'file' )) {
// Get data about the file
$uploadData = $this->upload->data ();
$filename = $uploadData ['file_name'];
// Initialize array
$data ['filenames'] [] = $filename;
}
}
}
Related
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 !
I am trying to upload multiple photos! My code is working but it's uploading only one photo - not all selected photos.
What's wrong in my code?
if(count($_FILES["userfile"]["name"]) == 0) {
$this->session->set_flashdata('success', '?? ????? ?????? ?????');
redirect('accidents/index');
}
else {
// configurations from upload library
$config['upload_path'] = './uploads/images';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['max_size'] = '2048000'; // max size in KB
$config['max_width'] = '20000'; //max resolution width
$config['max_height'] = '20000'; //max resolution height
// load CI libarary called upload
$this->load->library('upload', $config);
for($count = 0; $count < count($_FILES["userfile"]["name"]); $count++) {
// body of if clause will be executed when image uploading is failed
if(!$this->upload->do_upload()) {
$errors = array('error' => $this->upload->display_errors());
// This image is uploaded by deafult if the selected image in not uploaded
$image = 'no_image.png';
}
// body of else clause will be executed when image uploading is succeeded
else {
$data = array('upload_data' => $this->upload->data());
$image = $_FILES['userfile']['name']; //name must be userfile
}
$this->accidents_model->addphoto($image,$last_id);
}
}
And the model is:
public function addphoto($photo,$last_id) {
$data = array(
'cp_photo' => $photo,
'ac_id' => $last_id
);
//insert image to the database
$this->db->insert('cars_photos', $data);
}
i found the problem in my code in for loop it was upload one file after that redirected to index page ( this is mistake ) case the redirect line must be outside for loop :)
Here full working code after some modification with able to create folder for each user id (i take the code from stack usere here :) thanks alot )
in upload page i use
public function upload() {
$acc = $last_id;
$file_path = ".uploads/images/" . $acc . '/';
if (isset($_FILES['multipleUpload'])) {
if (!is_dir('uploads/images/' . $acc)) {
mkdir('.uploads/images/' . $acc, 0777, TRUE);
}
$files = $_FILES;
$cpt = count($_FILES ['multipleUpload'] ['name']);
$this->load->library('upload');
for ($i = 0; $i < $cpt; $i ++) {
$name = $files ['multipleUpload'] ['name'] [$i];
$_FILES ['multipleUpload'] ['name'] = $name;
$_FILES ['multipleUpload'] ['type'] = $files ['multipleUpload'] ['type'] [$i];
$_FILES ['multipleUpload'] ['tmp_name'] = $files ['multipleUpload'] ['tmp_name'] [$i];
$_FILES ['multipleUpload'] ['error'] = $files ['multipleUpload'] ['error'] [$i];
$_FILES ['multipleUpload'] ['size'] = $files ['multipleUpload'] ['size'] [$i];
$this->upload->initialize($this->set_upload_options($file_path));
if(!($this->upload->do_upload('multipleUpload')) || $files ['multipleUpload'] ['error'] [$i] !=0)
{
print_r($this->upload->display_errors());
}
else
{
$this->accidents_model->addphoto($name,$acc);
}
}
//======================================================================================
}
$this->session->set_flashdata('success', 'the files uploaded');
redirect('accidents/index'); // :) here must located outside for loop
}
}
public function set_upload_options($file_path) {
// upload an image options
$config = array();
$config ['upload_path'] = $file_path;
$config ['allowed_types'] = 'gif|jpg|png';
return $config;
}
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();
}
}
This is the View.php file
<input name="u_code[]" required="required" style="margin:0px; ">
<input name="u_name[]" required="required" style="margin:0px; ">
<input name="u_address[]" required="required" style="margin:0px; ">
<input name="photo[]" required="required" style="margin:0px; ">
This is my Controller inserting multiple data but I want to include upload photo.Unfortunately it will not run.
My table has a field for User ID, User Code, Username, User address the lastly the photo of each user.
function user_add()
{
if ($_POST)
{
$u_id =$this->input->post('u_id');
$u_code =$this->input->post('u_code');
$u_name =$this->input->post('u_name');
$u_address = $this->input->post('u_address');
if(!empty($_FILES['photo']['name']))
{
$upload = $this->_do_upload();
$data['photo'] = $upload;
} $data = array();
for ($i = 0; $i < count($this->input->post('u_id')); $i++)
{
$data[$i] = array(
'u_id' => $u_id[$i],
'u_code' => $u_code[$i],
'u_name' => $u_name[$i],
'u_address' => $u_address[$i],
);
}
$insert = $this->user_model->user_add($data);
echo json_encode(array("status" => TRUE));
}
}
This part is the function to upload photo.
public function photo_upload()
{
$config['upload_path'] = 'upload/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 100; //set max size allowed in Kilobyte
$config['max_width'] = 1000; // set max width image allowed
$config['max_height'] = 1000; // set max height allowed
$config['file_name'] = round(microtime(true) * 1000); //just milisecond timestamp fot unique name
$this->load->library('upload', $config);
if(!$this->upload->photo_upload('photo')) //upload and validate
{
$data['inputerror'][] = 'photo';
$data['error_string'][] = 'Upload error: '.$this->upload->display_errors('',''); //show ajax error
$data['status'] = FALSE;
echo json_encode($data);
exit();
}
return $this->upload->data('file_name');
}
**Model:**
public function user_add($data)
{
$this->db->insert_batch($this->table, $data);
return $this->db->insert_id();
}
This is the Actual forms picture:
I am trying to upload multiple images.
My form is this:
<form>
<input type="file" name="images[]">
<input type="file" name="images[]">
<input type="file" name="images[]">
</form>
I know that this form is right. I am getting an error when Codeigniter tries to upload a file.
function do_upload_images() {
$files = $_FILES;
$cpt = count ( $_FILES ['images'] ['name'] );
for($i = 0; $i < $cpt; $i ++) {
$_FILES ['images'] ['name'] = $files ['images'] ['name'] [$i];
$_FILES ['images'] ['type'] = $files ['images'] ['type'] [$i];
$_FILES ['images'] ['tmp_name'] = $files ['images'] ['tmp_name'] [$i];
$_FILES ['images'] ['error'] = $files ['images'] ['error'] [$i];
$_FILES ['images'] ['size'] = $files ['images'] ['size'] [$i];
$this->upload->initialize ( $this->set_upload_options () );
$this->upload->do_upload ($_FILES['images']);
}
}
private function set_upload_options() {
// upload an image options
$config = array ();
$config ['upload_path'] = './uploads/estate_images';
$config ['allowed_types'] = 'gif|jpg|png';
$config ['encrypt_name'] = TRUE;
return $config;
}
This is the error i got:
Message: Illegal offset type in isset or empty Filename:
libraries/Upload.php Line Number: 377
I get the solution by myself. Just needed to change the following line:
$this->upload->do_upload ($_FILES['images']);
to
$this->upload->do_upload ('images');