how to upload the image in codeigniter code example

Example 1: get upload error codeigniter

if($this->input->post())
{
   $file_element_name = 'image';  //this is the name of your input file. for example "image"
   if ($_FILES['image']['name']!= "")
   {
      $config['upload_path'] = './uploads/';
      $config['allowed_types'] = 'gif|jpg|png|exe|xls|doc|docx|xlsx|rar|zip';
      $config['max_size']      = '8192'; 
      $config['remove_spaces']=TRUE;  //it will remove all spaces
      $config['encrypt_name']=TRUE;   //it wil encrypte the original file name
      $this->load->library('upload', $config);

      if (!$this->upload->do_upload($file_element_name))
      {
         $error = array('error' => $this->upload->display_errors());
         $this->session->set_flashdata('error',$error['error']);
         redirect('controller_name/function_name','refresh');
      }
      else
      {
         $data = $this->upload->data();
         return $data['file_name'];          
      }
      $this->session->set_flashdata('msg','success message');
      redirect('controller_name/function_name','refresh');
   }
   else
   {
        //if no file uploaded the do stuff here
   } 
}

Example 2: upload image in codeigniter 3 source code

<!DOCTYPE html>
<html>
<head>
    <title>Image Upload Results</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
    <div>
        <h3>Congratulations, the image has successfully been uploaded</h3>
        <p>Click here to view the image you just uploaded
            <?=anchor('images/'.$image_metadata['file_name'], 'View My Image!')?>
        </p>

        <p>
            <?php echo anchor('upload-image', 'Go back to Image Upload'); ?>
        </p>
    </div>
</body>
</html>

Tags:

Misc Example