CodeIgniter Image Upload Script

In CodeIgniter, upload library is useful to upload image.

We need to add multipart in form, so we can upload file:

<?php echo form_open_multipart('upload/do_upload'); ?&gt;

and add input type as “file: to upload file:

<input type="file" name="profile_image" /&gt;

In controller function, you need to add upload library:

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

In $config, you add basic config setting:

$config['upload_path']          = './uploads/';  //folder path file to upload 
$config['allowed_types']        = 'gif|jpg|png'; //allowed file type or file extension  
$config['max_size']             = 100;    
$config['max_width']            = 300;  
$config['max_height']           = 400;

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

After that, do_upload function uploads file on specific folder location and $upload_data gives uploaded file information or return error based on performed operation result.

if ( ! $this-&gt;upload-&gt;do_upload('profile_image'))
{
    $error = array('error' =&gt; $this-&gt;upload-&gt;display_errors());
} else{
    $upload_data = $this-&gt;upload-&gt;data();
}

Upload script:

$config['upload_path']          = './uploads/'; 
$config['allowed_types']        = 'gif|jpg|png'; 
$config['max_size']             = 100;    
$config['max_width']            = 300;  
$config['max_height']           = 400;

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

if ( ! $this->upload->do_upload('userfile'))
{
    $error = array('error' => $this->upload->display_errors());
} else {
    $upload_data = $this->upload->data();
}

Hope this helps!

Leave a Reply