Tutorialsplane

Codeigniter File Upload


Codeigniter File Upload: Codeigniter provides uploading classes to upload the files. It provides several options to set restrictions(such as file size, file type) and preferences of the file. Here in this tutorial we are going to explain how you can upload files/Images in Codeigniter.


Codeigniter File Upload | Image Upload Library Example

Let us go step by step to understand how to upload files/images in Codeigniter.

Steps to Upload Files

Following steps are main steps to upload files in codeigniter-

Upload Form(Html View)

Create a view file as upload_form_view.php in application/views folder. This Html Form contains the form input to select and upload the file –

Codeigniter File Upload | Html Part Example:



<title>Upload File Form</title>



<?php echo $error;??>

<?php echo form_open_multipart('upload/process_upload');??>









Controller

Create a controller file as upload.php in application/controllers folder. This will contain the code to upload file on server as below-

Codeigniter File Upload Controller Example:

<?php class Upload extends CI_Controller {

        public function __construct()
        {
                parent::__construct();
                $this-?>load->helper(array('form', 'url'));
        }

        public function index()
        {
                $this->load->view('upload_form_view', array('error' => ' ' ));
        }

        public function process_upload()
        {
                $config['upload_path']          = './uploads/';
                $config['allowed_types']        = 'gif|jpg|png';
                $config['max_size']             = 2048;
                $config['max_width']            = 1000;
                $config['max_height']           = 800;
                $this->load->library('upload', $config);

                if ( ! $this->upload->process_upload('myfile'))
                {
                        $error = array('error' => $this->upload->display_errors());

                        $this->load->view('upload_form_view', $error);
                }
                else
                {
                        $data = array('upload_data' => $this->upload->data());

                        $this->load->view('success_view', $data);
                }
        }

}
?>

In controller method process_upload $config array is used to set the preferences and restrictions. Let us have look on the config –

Success Page(Html View)

Create a view file as success_view.php in application/views folder. This view will be loaded when the file is uploaded successfully.

Success Page View:



<title>Upload Success</title>



<h3>The file was successfully uploaded.</h3>

    $value):?>
  • :