Codeingiter file upload with validation

Codeingiter file upload with validation

Codeigniter is fastest and object oriented PHP Framework. Today, We are going to learn file upload functionality with validation. Codeigniter provides an library for image upload. We can easily create image upload functionality using Codeigniter upload library. Let’s start to Codeingiter file upload with validation.

First of all, We are going to create the controller for creating the image upload functionality. Before starting we need to install Codeigniter framework. I hope you install Codeigniter framework if not then follow this tutorial.

Codeingiter file upload functionality

Before creating the controller file first we create the route for that controller. So, let’s open the application/config/routes.php file and write the below routes.

$route['fileupload/create']['get'] = "fileupload/create";
$route['fileupload/store']['post'] = "fileupload/store";

After, Creating the routes now let’s create the fileupload controller. So let’s create new file at application/controllers/Fileupload.php. Now let’s write the code on controller file.

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Fileupload extends CI_Controller {

    public function __construct() {
        parent::__construct(); 

        $this->load->library('form_validation');
        $this->load->library('session');
        $this->load->helper('url');
        $this->load->model('FileuploadModel');
    }

    public function create()
    {
        $this->load->view('fileupload/create');
    }

    public function store()
    {
        $this->form_validation->set_rules('title', 'Title', 'trim|required');
        if (empty($_FILES['image']['name']))
        {
            $this->form_validation->set_rules('image', 'Image', 'required');
        }

        if ($this->form_validation->run() == FALSE){
            $this->session->set_flashdata('errors', validation_errors());
            redirect(base_url('fileupload/create'));
        }else{
            $config['upload_path']   = './uploads/fileupload/';
            $config['allowed_types'] = 'jpg|jpeg|png';
            $config['max_size']      = '1024';
            $config['max_width']     = '1200';
            $config['max_height']    = '800';
            $this->load->library('upload', $config);
            if ( !$this->upload->do_upload('image',FALSE))
            {
                $this->session->set_flashdata('errors', $this->upload->display_errors());
                redirect(base_url('fileupload/create'));
            }else{
                $imageData = $this->upload->data();
                $insert_data = [
                    'title' => $this->input->post('title'),
                    'image' => $imageData['file_name']
                ];
                $this->FileuploadModel->insert($insert_data);
                $this->session->set_flashdata('success', "Fileupload inserted succesfully.");
                redirect(base_url('fileupload/create'));
            }
        }
    }

}

We are ready with controller code Now let’s create model file Fileupload at application/models/FileuploadModel.php file and write the following code.

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

class FileuploadModel extends CI_Model{

    protected $table;

    public function __construct(){
        parent::__construct();

        $this->load->database();
        $this->table = "fileupload";
    }

    public function insert( $data = array() )
    {    
        return $this->db->insert($this->table, $data);
    }

    public function update( $data = array(), $id ) 
    {
        $this->db->where('id',$id);
        return $this->db->update($this->table,$data);
    }

    public function find($id)
    {
        return $this->db->get_where($this->table, array('id' => $id))->row();
    }

    public function delete($id)
    {
        return $this->db->delete($this->table, array('id' => $id));
    }
}
?>

Finally, We are ready with the model code and now let’s create the html interface view file. Let’s create the view file at application/views/fileupload/create.php file and write the following code.

<!DOCTYPE html>
<html>
<head>
    <title>Codeigniter - File upload example</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>

    <div class="container">
        <div class="row">
            <div class="col-md-12">
                <br>
                <div class="panel panel-default">
                    <div class="panel-heading">File upload Example</div>
                    <div class="panel-body">

                        <?php
                            if ($this->session->flashdata('errors')){
                                echo '<div class="alert alert-danger">';
                                echo $this->session->flashdata('errors');
                                echo "</div>";
                            }
                            if ($this->session->flashdata('success')){
                                echo '<div class="alert alert-success">';
                                echo $this->session->flashdata('success');
                                echo "</div>";
                            }
                        ?>

                        <form method="POST" action="<?php print base_url('fileupload/store'); ?>" enctype="multipart/form-data">
                            <div class="form-group">
                                <label for="title">Title</label>
                                <input type="text" name="title" class="form-control" id="title" placeholder="Title">
                            </div>

                            <div class="form-group">
                                <label for="exampleInputFile">File input</label>
                                <input type="file" name="image" id="exampleInputFile">
                                <p class="help-block">Select only jpg, jpeg, png file.</p>
                            </div>

                            <button type="submit" class="btn btn-primary">Submit</button>
                        </form>
                    </div>
                </div>

            </div>
        </div>
    </div>

</body>
</html>

Finally, we are ready with the Codeigniter image upload functionality. Now let’s runt the below URL and you will see the output something like

Codeingiter file upload with validation

Still, If you face any issue write the comment below.