How to upload images using codeigniter?

Member

by dedrick , in category: PHP CMS , 20 days ago

How to upload images using codeigniter?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by lily , 20 days ago

@dedrick 

To upload images using CodeIgniter, you can follow these steps:

  1. Create a form in your view file to allow users to select and upload an image. Make sure to set the form's enctype attribute to "multipart/form-data".
1
2
3
4
<form action="upload_image" method="post" enctype="multipart/form-data">
    <input type="file" name="image">
    <input type="submit" value="Upload">
</form>


  1. Create a controller method to handle the image upload. In the controller, use the CodeIgniter upload library to handle the file upload.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
public function upload_image() {
    $config['upload_path'] = './uploads/';
    $config['allowed_types'] = 'jpg|png|jpeg|gif';
    $config['max_size'] = 10240;

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

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


  1. Make sure to create an "uploads" folder in your CodeIgniter project root directory to store the uploaded images.
  2. Don't forget to set the correct permissions on the "uploads" folder to allow the web server to write to it.
  3. Test the image upload feature by selecting an image file in the form and submitting it. The uploaded image should be saved in the "uploads" folder.


That's it! You have successfully implemented image upload functionality using CodeIgniter.