How to upload image in Codeigniter?

by elisha_langworth , in category: PHP Frameworks , 9 months ago

How to upload image in Codeigniter?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by deron , 3 months ago

@elisha_langworth 

To upload an image in CodeIgniter, you will need to follow these steps:

  1. Create a form in your view file with an input element of type file and a submit button.
1
2
3
4
5
<form method="post" action="<?php echo base_url('upload/do_upload'); ?>" enctype="multipart/form-data">
    <input type="file" name="userfile" size="20" />
    <br /><br />
    <input type="submit" value="upload" />
</form>


  1. In your controller, create a method to handle the form submission. In this method, you will use the upload library to handle the file upload.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public 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;

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

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

        $this->load->view('upload_form', $error);
    }
    else
    {
        $data = array('upload_data' => $this->upload->data());

        $this->load->view('upload_success', $data);
    }
}


  1. In the $config array, specify the upload path, allowed file types, and other options such as maximum size and dimensions.
  2. Load the upload library and pass it the $config array.
  3. Use the do_upload method of the upload library to handle the actual file upload. If the upload is successful, the uploaded file data will be returned in the $data array. If the upload fails, an error message will be returned in the $error array.
  4. Depending on the result of the upload, you can either display an error message or a success message, along with any relevant data such as the uploaded file name or size.