We will learn how to upload image with validation in PHP Codeigniter?


Step 1: 

Download Fresh Codeigniter 3: Download Codeigniter 3


Step2:  

Add Route application/config/routes.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');


$route['default_controller'] = 'welcome';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;
$route['image-upload'] = 'ImageUpload';
$route['image-upload/post']['post'] = "ImageUpload/uploadImage";


Step 3:

Create Controller application/controllers/ImageUpload.php

<?php


class ImageUpload extends CI_Controller {


   /**
    * Manage __construct
    *
    * @return Response
   */
   public function __construct() { 
      parent::__construct(); 
      $this->load->helper(array('form', 'url')); 
   }


   /**
    * Manage index
    *
    * @return Response
   */
   public function index() { 
      $this->load->view('imageUploadForm', array('error' => '' )); 
   } 


   /**
    * Manage uploadImage
    *
    * @return Response
   */
   public function uploadImage() { 


      $config['upload_path']   = './uploads/'; 
      $config['allowed_types'] = 'gif|jpg|png'; 
      $config['max_size']      = 1024;
      $this->load->library('upload', $config);


      if ( ! $this->upload->do_upload('image')) {
         $error = array('error' => $this->upload->display_errors()); 
         $this->load->view('imageUploadForm', $error); 
      }else { 
         print_r('Image Uploaded Successfully.');
         exit;
      } 
   }


} 


?>


Step 4: 

Create View application/views/imageUploadForm.php

<!DOCTYPE html>
<html> 
<head> 
  <title>Image Upload Example from Scratch</title> 
</head>


<body> 


  <?php echo $error;?> 
  <?php echo form_open_multipart('image-upload/post');?> 
     <input type="file" name="image" size="20" />
     <input type="submit" value="upload" /> 
  </form> 


</body>
</html>

Now you can run this example.