How to upload picture using codeigniter?

Member

by dedrick , in category: PHP Frameworks , 7 months ago

How to upload picture using codeigniter?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by adan , 7 months ago

@dedrick 

To upload a picture using CodeIgniter, you can follow these steps:

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


  1. Create a method in your controller to handle the picture upload:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
public function upload_picture(){
    $config['upload_path'] = './uploads/'; //set the upload directory
    $config['allowed_types'] = 'gif|jpg|png'; //set allowed file types
    $this->load->library('upload', $config);
    
    if (!$this->upload->do_upload('userfile')) {
        $error = array('error' => $this->upload->display_errors());
        //handle the error as needed
    } else {
        $data = array('upload_data' => $this->upload->data());
        //save the file info to the database or display success message
    }
}


  1. Make sure you have created a folder named 'uploads' in your CodeIgniter project root directory to store the uploaded pictures.
  2. Make sure the folder has write permissions so that CodeIgniter can save the uploaded pictures in it.
  3. That's it! Now when a user selects and uploads a picture through the form, the picture will be uploaded to the 'uploads' folder and you can save the file information to the database or display a success message.