2

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

Christian Giupponi
  • 7,408
  • 11
  • 68
  • 113
Roopa Shree
  • 23
  • 1
  • 5

2 Answers2

1

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.

Harish
  • 462
  • 6
  • 13
  • `value is inserting twice` but insert is outside the loop so it should insert only once. May be you are resubmitting the form twice? – Harish Sep 20 '17 at 14:30
  • @RoopaShree I checked and run the complete script on my system with database and its working perfectly fine, I don't know why are you getting this error without any logic, Have you really executed this code? Please if you really getting some error then comment with the proper error. – Harish Sep 20 '17 at 19:40
  • @RoopaShree Yes sure I'll but see your initial problem is resolved right so can you please accept this answer as accepted. – Harish Sep 21 '17 at 14:30
  • I have modified my code according to your code but the problem I am facing is if I will add more than 5 it will not take.I am not understanding why this happening – Roopa Shree Sep 21 '17 at 18:17
  • And I have taken stored value in session , if form is empty then it should take session value but It is not uploading can you please tell me how to do – Roopa Shree Sep 21 '17 at 18:18
  • May the images size is too big and if its taking more than 30 seconds then you need to increase your default php execution time, Please you can follow this https://stackoverflow.com/questions/7739870/increase-max-execution-time-for-php. – Harish Sep 21 '17 at 18:59
  • You can edit your question with your view file where is your form, controller script and model (if you are using model ) then I can clearly understand your issue and will help you to resolve that. – Harish Sep 21 '17 at 19:17
  • Your code is working perfectly but only 5 images it's taking not more then 5 images can you please solve this problem – Roopa Shree Sep 22 '17 at 17:09
  • please check in your only 5 images it will take not more then that – Roopa Shree Sep 22 '17 at 17:29
  • @Roopa, Sorry I was not able to work in last three days. I hope you have solved your issues :) – Harish Sep 25 '17 at 14:35
0

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();
            }

}
Yasir Ali
  • 21
  • 6