Easy Image and File Upload in CodeIgniter with Validations & Examples

Easy Image and File Upload in CodeIgniter with Validations & Examples

Codeigniter provides a wide number of helper class and libraries for rapid application development. Upload library is one among them that makes file uploading process in Codeigniter a breeze. We'll see how to do file and image upload in codeigniter in this tutorial.

File Upload in CodeIgniter

First of all, we need a destination folder to store all the uploaded files. So create a folder named 'uploads' in the root folder. Make sure it is writable for the uploading process to work.

Create Controller

Create a controller file 'uploadfile.php' inside 'application\controllers' folder in codeigniter.
<?php
class uploadfile extends CI_Controller {

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

    //index function
    function index()
    {
        //load file upload form
        $this->load->view('upload_file_view');
    }

    //file upload function
    function upload()
    {
        //set preferences
        $config['upload_path'] = './uploads/';
        $config['allowed_types'] = 'txt|pdf';
        $config['max_size']    = '100';

        //load upload class library
        $this->load->library('upload', $config);

        if (!$this->upload->do_upload('filename'))
        {
            // case - failure
            $upload_error = array('error' => $this->upload->display_errors());
            $this->load->view('upload_file_view', $upload_error);
        }
        else
        {
            // case - success
            $upload_data = $this->upload->data();
            $data['success_msg'] = '<div class="alert alert-success text-center">Your file <strong>' . $upload_data['file_name'] . '</strong> was successfully uploaded!</div>';
            $this->load->view('upload_file_view', $data);
        }
    }
}
?>
The upload() method in the codeigniter controller is where the actual file upload process takes place. Here we load the 'upload' library with the statement $this->load->library('upload', $config); . The $config is the array where we set preferences to control the uploading process. This is where we define the file uploading path, allowed file extensions, maximum file size etc.
This controller upload() method will be invoked on form submission, and the file will be validated and shows the validation error in case it fails. Else it will upload the file to the destination folder.
We have used some of the important methods of the 'upload' class library in our controller.
  1. The callback, $this->upload->do_upload() will upload the file selected in the given field name to the destination folder. Note that the parameter to this method is optional and if it is not mentioned, then it expects the file from the input field with name 'userfile'. So if you set the file input with name other than 'userfile' make sure you pass the field name as parameter to the do_upload()function.
  2. The callback $this->upload->display_errors() returns the error message if the do_upload() method returns false.
  3. And the callback $this->upload->data() returns an array of data related to the uploaded file like the file name, path, size etc.

Create View

Create the view file 'upload_file_view.php' inside 'application\views' folder. This view file contains a simple upload form with file input and a submit button.
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CodeIgniter File Upload Form</title>
    <!-- load bootstrap css file -->
    <link href="<?php echo base_url("assets/bootstrap/css/bootstrap.css"); ?>" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-md-6 col-md-offset-3 well">
        <legend>CodeIgniter File Upload Demo</legend>
        <?php echo form_open_multipart('uploadfile/upload');?>

        <fieldset>
            <div class="form-group">
                <div class="row">
                    <div class="col-md-12">
                        <label for="filename" class="control-label">Select File to Upload</label>
                    </div>
                </div>
            </div>

            <div class="form-group">
                <div class="row">
                    <div class="col-md-12">
                        <input type="file" name="filename" size="20" />
                        <span class="text-danger"><?php if (isset($error)) { echo $error; } ?></span>
                    </div>
                </div>
            </div>

            <div class="form-group">
                <div class="row">
                    <div class="col-md-12">
                        <input type="submit" value="Upload File" class="btn btn-primary"/>
                    </div>
                </div>
            </div>
        </fieldset>
        
        <?php echo form_close(); ?>
        <?php if (isset($success_msg)) { echo $success_msg; } ?>
        </div>
    </div>
</div>
</body>
</html>
The above view will produce an upload form like this.
codeigniter-file-upload-demo-form
CodeIgniter File Upload Demo Form
Generally I use bootstrap css framework to design the html forms for all my tutorials. This tutorial is no exception and I have used bootstrap components to give a nice look and feel to our upload form. Also I have set the form type to 'multipart' for the file uploading to work. (If you are a newbie to bootstrap then take a look at this tutorial on using bootstrap with codeigniter php framework to learn more).
When the user submits the form, it will be validated against the preferences set by the $config[] array. If the file is not selected or any other form validation error occurs, it is displayed below the file input like this.
file-upload-validation-error
If the validation succeeds and the file is uploaded successfully to the destination folder, a success message will be displayed at the bottom of the form like this.
file-upload-validation-success

Uploading Images in CodeIgniter

If you want to restrict the user to upload only image files in codeigniter, then you can set the preferences to something like this in the controller file,
<?php
    $config['upload_path'] = './uploads/';
    $config['allowed_types'] = 'png|jpg|gif';
    $config['max_size'] = '150';
    $config['max_width'] = '1024'; /* max width of the image file */
    $config['max_height'] = '768'; /* max height of the image file */
?>
Hence in this way you can restrict the users to upload only images. Moreover all those image files should fall under the maximum file size, width and height set by you :).
And that explains the file and image uploading process in codeigniter.

No comments:

Post a Comment