File Uploading Class

CodeIgniter is support File Uploading Class permits files to be uploaded. You can set various preferences and restricting the type and size of the files.

Create a view called upload.php. Place the following code in it and save this file to application/views/ directory. upload.php file contains form HTML, it is used to collect the user data and submit to the controller.

<?php echo $this->session->flashdata('success_msg'); ?>
<?php echo $this->session->flashdata('error_msg'); ?>
<form role="form" method="post" enctype="multipart/form-data">
    <div class="panel">
        <div class="panel-body">
            <div class="form-group">
                <label>Picture</label>
                <input class="form-control" type="file" name="picture" />
            </div>
             <div class="form-group">
                <input type="submit" class="btn btn-warning" name="userSubmit" value="Upload">
            </div>
        </div>
    </div>
</form>

Create a controller called UploadController.php. Place the following code in it and save this file to application/controllers/ directory.

Initially, upload() function will load the upload adding form. When the form is submitted then picture would be uploaded.

<?php defined('BASEPATH') OR exit('No direct script access allowed');
class UploadController extends CI_Controller
{
    function  __construct() {
        parent::__construct();
    }
    
    function upload(){
        if($this->input->post('userSubmit')){
            
            if(!empty($_FILES['picture']['name'])){
                $config['upload_path'] = 'uploads/';
                $config['allowed_types'] = 'jpg|jpeg|png|gif';
                $config['file_name'] = $_FILES['picture']['name'];
                
                $this->load->library('upload',$config);
                $this->upload->initialize($config);
                
                if($this->upload->do_upload('picture')){
                    $uploadData = $this->upload->data();
                    $this->session->set_flashdata('success_msg', 'User data have been added successfully.');
                }else{
                    $this->session->set_flashdata('error_msg', 'Some problems occured, please try again.');
                }
            }
            
        }
        $this->load->view('upload');
    }
}
?>

Creating Upload Directory in root folder:

Create the uploads/ directory to storing the uploaded images.

After you enter the following URL :

https://howtowebcode.com/UploadController/upload