How to upload image in codeigniter?

Member

by domenico , in category: PHP Frameworks , 8 months ago

How to upload image in codeigniter?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by giovanny.lueilwitz , 8 months ago

@domenico 

To upload an image in Codeigniter, you can use the following steps:

  1. Create a form in your view file to allow users to select and upload an image:
1
2
3
4
<form method="post" action="upload_image" enctype="multipart/form-data">
    <input type="file" name="userfile" />
    <input type="submit" value="Upload Image" />
</form>


  1. Create a controller function to handle the uploaded image:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
public function upload_image() {
    $config['upload_path'] = './uploads/'; // Set the upload path for the image
    $config['allowed_types'] = 'jpg|jpeg|png|gif'; // Set allowed image types
    $config['max_size'] = 1024; // Set max file size in KB

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

    if (!$this->upload->do_upload('userfile')) { // Check if image is uploaded successfully
        $error = array('error' => $this->upload->display_errors());
        print_r($error);
    } else {
        $data = array('upload_data' => $this->upload->data());
        print_r($data);
    }
}


  1. Create a folder named "uploads" in the root directory of your Codeigniter application to store the uploaded images.
  2. Make sure to set the correct file permissions for the "uploads" folder to allow Codeigniter to write to it.
  3. After uploading the image successfully, you can save the image file path to your database or perform any other actions as needed.


By following these steps, you can easily upload an image in Codeigniter.