Member Avatar for anmol.raghuvanshi1

In my registration page i want user to select multiple images and upload it i am saving images name in database for reference. I am successful in uploading single images in database and can also show image in view but now i have problem in uploading multiple images.

<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');

ini_set("display_errors",1);

class Update_profile extends CI_Controller {

      var $file_path;  //for original image
      var $file_path_url; //for thumbnails


     function __construct()
     {
          // Call the Model constructor
          parent::__construct();
          $this->load->library('session');
          $this->is_login();
          $this->load->helper(array('form', 'url'));
         $this->load->model('Edit_profile');
          //return full path of directory
          //Make sure these directory have read and write permission
          $this->file_path = realpath(APPPATH . '../upload/large');
          $this->file_path_url = realpath(APPPATH.'../upload/thumbs/');

         // $this->load->model('Insert_article');        
     }


    public  function index() {

        $this->load->view('header');
        $this->load->view('edit_profile');

    }// index function ends


  // function to upload images
    function upload()
    {
        //loading image class
        $session_data = $this->session->userdata('sessiondata');
        $user_id = $session_data['user_id'];
        //post image
        $img=$this->input->post("filename");

        //set preferences
        $config['remove_spaces']=TRUE;
        $config['encrypt_name'] = TRUE; // for encrypting the name
        $config['upload_path'] = LARGEPATH;
        $config['allowed_types'] = 'jpg|png|gif';
        $config['max_size']    = '78000';

        //load moadel ********
        $this->load->model('Edit_profile');

        //load upload class library
        $this->load->library('upload', $config);

        //$this->upload->do_upload('filename') will upload selected file to destiny folder
        if (!$this->upload->do_upload('filename'))
        {
            // case - failure
            $upload_error = array('error' => $this->upload->display_errors());
            $this->load->view('edit_profile', $upload_error);
        }
        else
        {
            // case - success
            //callback  returns an array of data related to the uploaded file like the file name, path, size etc
            $upload_data = $this->upload->data();


            // call to model function *********
            $data['images'] = $this->Edit_profile->insert_new_post($upload_data);

            //now creating thumbnails

            $config1 = array(

                    'source_image'      => $upload_data['full_path'],
                    'create_thumb'      =>true,
                    'overwrite'         =>true,
                    'maintain_ratio'    =>true,
                    'new_image'         => THUMBPATH,
                    'thumb_marker'   =>'',
                    'maintain_ratio'    => true,
                    'width'             => 128,
                    'height'            => 128
                    );
                /// print_r($config1);
                    //print_r(LARGEPATH.$upload_data['file_name']);
                    $this->load->library('image_lib');
                    $this->image_lib->initialize($config1);
                    $this->image_lib->resize();
                    if ( ! $this->image_lib->resize()){echo $this->image_lib->display_errors();}
                    $this->image_lib->clear();

                //  echo $this->image_lib->display_errors(); 
            //here is the second thumbnail, notice the call for the initialize() function again
            //$this->image_lib->initialize($config);
            //$this->image_lib->resize();
            //$data['success_msg'] = '<div class="alert alert-success text-center">Your file <strong>' .$upload_data['file_name']. '</strong> was successfully uploaded!</div>';
             //$this->load->view('edit_profile', $data);

            $this->session->set_flashdata('success_msg', '<div class="alert alert-success text-center">Your file <strong>' . '</strong> was successfully uploaded!</div>');
            redirect(base_url("Update_profile/index"));

        }  




    }




} //class ends   
?>

Above code is working for uploading single image and saving name of image in database and creating thumnails also and then i changed it to

    function upload()
    {
                $name_array = array();
                $count = count($_FILES['file']['size']);
                foreach($_FILES as $key=>$value)
                for($s=0; $s<=$count-1; $s++) {
                $_FILES['file']['name']=$value['name'][$s];
                $_FILES['file']['type']    = $value['type'][$s];
                $_FILES['file']['tmp_name'] = $value['tmp_name'][$s];
                $_FILES['file']['error']       = $value['error'][$s];
                $_FILES['file']['size']    = $value['size'][$s]; 

                //set preferences
                $config['remove_spaces']=TRUE;
                $config['encrypt_name'] = TRUE; // for encrypting the name
                $config['upload_path'] = LARGEPATH;
                $config['allowed_types'] = 'jpg|png|gif';
                $config['max_size']    = '78000';


                //load moadel ********
                $this->load->model('Image_gallery');

                //load upload class library
                $this->load->library('upload', $config);

                    if(!$this->upload->do_upload('file'))
                {
                   // case - failure
                    $upload_error = array('error' => $this->upload->display_errors());
                    $this->load->view('gallery', $upload_error);
                }
                else
                {
                   // case - success
                    //callback  returns an array of data related to the uploaded file like the file name, path, size etc
                    $upload_data = $this->upload->data();
                    //$data = $this->upload->data();
                    $name_array[] = $upload_data['file_name']; //success till here now inserting in database and creating thumbnails
                    $data['images'] = $this->Image_gallery->insert_new_post($upload_data);

                    $this->session->set_flashdata('success_msg', '<div class="alert alert-success text-center">Your file <strong>' . '</strong> was successfully uploaded!</div>');
                    redirect(base_url("Image_upload/index"));



                }

            }

Finally my model

     function insert_new_post($upload_data)
{

    $session_data = $this->session->userdata('sessiondata');
    $user_id = $session_data['user_id'];

    $filePath = $upload_data['file_name'];
    //print_r(LARGEPATH);
    $query = "UPDATE `tbl_usrs` set profile_picture='".$filePath."' where user_id='".$user_id."'";
   // $this->db->query($query,array($img));
   $arg=array ($upload_data);

    if($this->db->query($query,$arg)==true)
        {
            return true; // if added to database
        }else {
                return false;
        }

}

So how can i change my model so that for given login user it can upload multiple image and name of those images is saved in database.

Thnks in advance

Recommended Answers

All 8 Replies

Member Avatar for anmol.raghuvanshi1

can anyone help me in this??

It would be helpful to know how you upload multiple images:

  1. are you using an array?

    <input type="file" name="image[]">
    
  2. or different names?

    <input type="file" name="image_1">
    <input type="file" name="image_2">
    <input type="file" name="image_3">
    <input type="file" name="image_4">
    <input type="file" name="image_5">
    

Because in first case you must loop the $_FILES array to get each image information, for more information follow these instructions:

Or simply print the contents of the $_FILES array to see the format of the received request.

Member Avatar for anmol.raghuvanshi1

I am using array.
that's actually i have done but problem is when i select multiple images it uploads only one

So,

in the controller you're trying to rewrite the $_FILES array to condition the execution of line 27:

if(!$this->upload->do_upload('file'))

Ok, then replace lines 4, 5 and 6 with:

$files = $_FILES;

foreach($files as $key => $value)
{
    for($s = 0; $s < count($files['file']['size']); $s++)
    {

The $files variable will hold a copy of the original $_FILES array. Otherwise the loop will stop because you're overwriting the $_FILES array and it cannot continue. A test method:

public function upload()
{
    $files = $_FILES;

    print '<h3>Original $_FILES array:</h3>';
    print "<pre>" . print_r($_FILES, true) . "</pre>";

    foreach($files as $key => $value)
    {
        for($s = 0; $s < count($files['file']['size']); $s++)
        {
            $_FILES['file']['name']     = $value['name'][$s];
            $_FILES['file']['type']     = $value['type'][$s];
            $_FILES['file']['tmp_name'] = $value['tmp_name'][$s];
            $_FILES['file']['error']    = $value['error'][$s];
            $_FILES['file']['size']     = $value['size'][$s]; 

            $config['upload_path']   = FCPATH . 'uploads/';
            $config['allowed_types'] = 'gif|jpg|png';

            $this->load->library('upload', $config);
            $this->upload->do_upload('file');

            print "<hr>";

            print '<h3>Rewritten $_FILES array number #'.$s.':</h3>';
            print "<pre>" . print_r($_FILES, true) . "</pre>";

            print "<h3>Upload data:</h3>";
            print "<pre>" . print_r($this->upload->data(), true) . "</pre>";

            print "<h3>Errors:</h3>";
            print "<pre>" . print_r($this->upload->display_errors(), true) . "</pre>";

        }
    }
}
Member Avatar for anmol.raghuvanshi1

Thnks test method helps me a lot

hmm, can you help me, if the structure like this.
<input type="file" name="image_1">
<input type="file" name="image_2">
<input type="file" name="image_3">
<input type="file" name="image_4">
<input type="file" name="image_5">

Hi, this should work:

public function upload_multi()
{
    $config['upload_path']   = FCPATH . 'uploads/';
    $config['allowed_types'] = 'gif|jpg|png';
    $config['remove_spaces'] = TRUE;
    $config['encrypt_name']  = TRUE;
    $config['max_size']      = '10000';
    $config['overwrite']     = FALSE;

    $this->load->library('upload', $config);

    # upload
    foreach($_FILES as $key => $value)
    {
        if($value['error'] == 0 && $value['size'] > 0)
        {
            $this->upload->do_upload($key);
            $upload['data'][$key] = $this->upload->data();
        }

        else
            # @see http://php.net/manual/en/features.file-upload.errors.php
            # and also if: (size == 0 && error == 0) then file is empty
            $upload['errors'][$key] = "Error: {$value['error']}";
    }

    print "<hr>";

    print '<h3>$_FILES:</h3>';
    print "<pre>" . print_r($_FILES, true) . "</pre>";

    print "<h3>Upload data:</h3>";
    print "<pre>" . print_r($upload['data'], true) . "</pre>";

    print "<h3>Errors:</h3>";
    print "<pre>" . print_r($upload['errors'], true) . "</pre>";
}

The $upload array will hold the data for each uploaded image and eventual errors. (And will probably work also for the previous question, not sure what I was thinking when answered...).

Bye!

Thank you for providing solutions to upload multiple image, Really it helpful for me.

"Thanks for support"

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.