18

In view

 <?php echo form_open_multipart('welcome/do_upload');?>
 <input type="file" name="userfile" size="20" />

In controler

function do_upload()
{
    $config['upload_path'] = './uploads/';
    $config['allowed_types'] = 'gif|jpg|png';
    $config['max_size'] = '100';
    $config['max_width']  = '1024';
    $config['max_height']  = '768';
    $config['overwrite'] = TRUE;
    $config['encrypt_name'] = FALSE;
    $config['remove_spaces'] = TRUE;
    if ( ! is_dir($config['upload_path']) ) die("THE UPLOAD DIRECTORY DOES NOT EXIST");
    $this->load->library('upload', $config);
    if ( ! $this->upload->do_upload('userfile')) {
        echo 'error';
    } else {

        return array('upload_data' => $this->upload->data());
    }
}

And I call this function like this

 $this->data['data'] = $this->do_upload();

and view this image:

<ul>
<?php foreach ($data['upload_data'] as $item => $value):?>
<li><?php echo $item;?>: <?php echo $value;?></li>
<?php endforeach; ?>
</ul>

I don't know what's the error.

15
  • 2
    Write <?php var_dump($data['upload_data']); ?> in your view and check the result. as a side-note: do NOT echo 'error' in controller when uploading fails. Commented Jun 26, 2013 at 9:19
  • It gives me null. I want to ask one question where upload folder put? Commented Jun 26, 2013 at 9:24
  • When you set ./uploads/ as upload folder, it should located at the root of your CodeIgniter installation (near of index.php). Commented Jun 26, 2013 at 9:29
  • It seems there is something wrong in your controller, please post further info. Commented Jun 26, 2013 at 9:31
  • I put this folder near index.php but still it gives me null output. Commented Jun 26, 2013 at 9:37

8 Answers 8

17

It seems the problem is you send the form request to welcome/do_upload, and call the Welcome::do_upload() method in another one by $this->do_upload().

Hence when you call the $this->do_upload(); within your second method, the $_FILES array would be empty.

And that's why var_dump($data['upload_data']); returns NULL.

If you want to upload the file from welcome/second_method, send the form request to the welcome/second_method where you call $this->do_upload();.

Then change the form helper function (within the View) as follows1:

// Change the 'second_method' to your method name
echo form_open_multipart('welcome/second_method');

File Uploading with CodeIgniter

CodeIgniter has documented the Uploading process very well, by using the File Uploading library.

You could take a look at the sample code in the user guide; And also, in order to get a better understanding of the uploading configs, Check the Config items Explanation section at the end of the manual page.

Also there are couple of articles/samples about the file uploading in CodeIgniter, you might want to consider:

Just as a side-note: Make sure that you've loaded the url and form helper functions before using the CodeIgniter sample code:

// Load the helper files within the Controller
$this->load->helper('form');
$this->load->helper('url');

// Load the helper files within the application/config/autoload
$autoload['helper'] = array('form', 'url');


1. The form must be "multipart" type for file uploading. Hence you should use `form_open_multipart()` helper function which returns: ``
Sign up to request clarification or add additional context in comments.

4 Comments

I stumbled on this Q&A from a Google search for another question. You may want to update your answer with the following link codeigniter.com/userguide3/libraries/… as the ellislab.com/codeigniter/user-guide/libraries/… library is out of date.
@Fred-ii- Thank you Fred. The answer is almost 3 yrs old :) and I hadn't had the chance to come back to it. Will update the answer with v3 ASAIC.
i have found this tutorial regarding this cloudways.com/blog/codeigniter-upload-file-image
uploading file in the same time sending the post variable would it be possible?
11

Simple Image upload in codeigniter

Find below code for easy image upload:

public function doupload()
     {
        $upload_path="https://localhost/project/profile"  
        $uid='10'; //creare seperate folder for each user 
        $upPath=upload_path."/".$uid;
        if(!file_exists($upPath)) 
        {
                   mkdir($upPath, 0777, true);
        }
        $config = array(
        'upload_path' => $upPath,
        'allowed_types' => "gif|jpg|png|jpeg",
        'overwrite' => TRUE,
        'max_size' => "2048000", 
        'max_height' => "768",
        'max_width' => "1024"
        );
        $this->load->library('upload', $config);
        if(!$this->upload->do_upload('userpic'))
        { 
            $data['imageError'] =  $this->upload->display_errors();
             
        }
        else
        {
            $imageDetailArray = $this->upload->data();
            $image =  $imageDetailArray['file_name'];
        }
        
     }

2 Comments

how about the data form submitted when we do uploading image, is it possible @Hiren?
yes it's possible, you can pass data along with image
3
//this is the code you have to use in you controller 

        $config['upload_path'] = './uploads/';  

// directory (http://localhost/codeigniter/index.php/your directory)

        $config['allowed_types'] = 'gif|jpg|png|jpeg';  
//Image type  

        $config['max_size'] = 0;    

 // I have chosen max size no limit 
        $new_name = time() . '-' . $_FILES["txt_file"]['name']; 

//Added time function in image name for no duplicate image 

        $config['file_name'] = $new_name;

//Stored the new name into $config['file_name']

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

        if (!$this->upload->do_upload() && !empty($_FILES['txt_file']['name'])) {
            $error = array('error' => $this->upload->display_errors());
            $this->load->view('production/create_images', $error);
        } else {
            $upload_data = $this->upload->data();   
        }

2 Comments

How do you pass $error ti the view without getting any errors?
is it possible posting the data as well while uploading?
0

Change the code like this. It works perfectly:

public function uploadImageFile() //gallery insert
{ 
    if($_SERVER['REQUEST_METHOD'] == 'POST') {
    $new_image_name = time() . str_replace(str_split(' ()\\/,:*?"<>|'), '', 
    $_FILES['image_file']['name']);
    $config['upload_path'] = 'uploads/gallery/'; 
    $config['allowed_types'] = 'gif|jpg|png|bmp|jpeg';
    $config['file_name'] = $new_image_name;
    $config['max_size']  = '0';
    $config['max_width']  = '0';
    $config['max_height']  = '0';
    $config['$min_width'] = '0';
    $config['min_height'] = '0';
    $this->load->library('upload', $config);
    $upload = $this->upload->do_upload('image_file');
    $title=$this->input->post('title');
    $value=array('title'=>$title,'image_name'=>
    $new_image_name,'crop_name'=>$crop_image_name);}

1 Comment

is this call executed from a multipart-form POST entry? i just wondering the form submitted whole data along with the image succesfully....
0
$image_folder = APPPATH . "../images/owner_profile/" . $_POST ['mob_no'] [0] . $na;
            if (isset ( $_FILES ['image'] ) && $_FILES ['image'] ['error'] == 0) {
                list ( $a, $b ) = explode ( '.', $_FILES ['image'] ['name'] );
                $b = end ( explode ( '.', $_FILES ['image'] ['name'] ) );
                $up = move_uploaded_file ( $_FILES ['image'] ['tmp_name'], $image_folder . "." . $b );
                $path = ($_POST ['mob_no'] [0] . $na . "." . $b);

3 Comments

See... First create <form> then add multipart tag for that form, means you can upload images to it. then put the name of that image tag i.e. "image"
then in codeigniter controller , write the above code
so your image will save in perticular folder and only the name of that image will store in the database tables
0

Below code for an uploading a single file at a time. This is correct and perfect to upload a single file. Read all commented instructions and follow the code. Definitely, it is worked.

public function upload_file() {
    ***// Upload folder location***
    $config['upload_path'] = './public/upload/';

    ***// Allowed file type***
    $config['allowed_types'] = 'jpg|jpeg|png|pdf';

    ***// Max size, i will set 2MB***
    $config['max_size'] = '2024';

    $config['max_width'] = '1024';
    $config['max_height'] = '768';

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

    ***// do_upload is the method, to send the particular image and file on that 
       // particular 
       // location that is detail in $config['upload_path']. 
       // In bracks will set name upload, here you need to set input name attribute 
       // value.***

    if($this->upload->do_upload('upload')) {
       $data = $this->upload->data();
       $post['upload'] = $data['file_name'];
    } else {
      $error = array('error' => $this->upload->display_errors());
    }
 }

Comments

0

check $this->upload->initialize($config); this works fine for me

    $new_image_name = "imgName".time() . str_replace(str_split(' ()\\/,:*?"<>|'), '', 
    $_FILES['userfile']['name']);
    $config = array();
    $config['upload_path'] = './uploads/'; 
    $config['allowed_types'] = 'gif|jpg|png|bmp|jpeg';
    $config['file_name'] = $new_image_name;
    $config['max_size']  = '0';
    $config['upload_path'] = './uploads/';
    $config['allowed_types'] = 'gif|jpg|png|mp4|jpeg';
    $config['file_name'] = url_title("imgsclogo");
    $config['max_size']      = '0';
    $config['overwrite']     = FALSE; 
    $this->upload->initialize($config);
    $this->upload->do_upload();
    $data = $this->upload->data();
}

Comments

0

In controller

 public function add_category(){
    $return_array = ['status' => false, 'message' => ''];

    // Retrieve input values
    $name = $this->input->post('name');
    $image = $_FILES['image']; // Get the uploaded file

    if ($image && $image['name']) {
        // Prepare the image name
        // $extension = pathinfo($image['name'], PATHINFO_EXTENSION);
        $Image1=explode('.', $image);
        $time = time();
        $image_name = $time . '.' . $extension;

        // Configure upload settings
        $config['upload_path'] = './Assets/Admin/hospitals';
        $config['allowed_types'] = 'jpg|jpeg|png';
        $config['file_name'] = $image_name;
        $config['max_size'] = 2048; // Maximum size in KB (2 MB)

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

        // Attempt to upload the file
        if ($this->upload->do_upload('image')) {
            // File uploaded successfully
            $upload_data = $this->upload->data(); // Get uploaded data
            $created_data = [
                'name' => $name,
                'image' => $upload_data['file_name'], // Store the image name in the database
            ];

            $this->load->model('User_model');
            $add_category = $this->User_model->add_category_model($created_data);
            if ($add_category) {
                $return_array['status'] = true;
                $return_array['message'] = 'Category added successfully.';
                $return_array['redirect_url'] = site_url('dashboard'); 
            }else
            {
                $return_array['message'] = 'Failed Try Again.';
            }
        } else {
            // Handle upload error
            $return_array['message'] = $this->upload->display_errors();
        }
    } else {
        $return_array['message'] = 'Please upload an image.';
    }
    // Return JSON response
    echo json_encode($return_array);
}

1 Comment

Although this code might answer the question, I recommend that you also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.