Thumbnail creation example in Codeigniter 2.1.4. There is a file upload class, in codeigniter, which permits you to upload the file or files and also we can create thumbnail for the uploaded file as per our desired size. This class also permits you to set various preferences such as destination where the file and thumbnail will be uploaded, restrition on file types, restriction on file size, whether a file name should be encrypted or not, maximum length of the file name etc.

Below are the simple few processes for uploading a file and thumbnail creation example in codeigniter for this uploaded file.
A form with input type file is required so that user can select the file using the browse button.

When the form is submitted, the file is validated to make sure that the file and thumbnail are uploaded against the preferences you set.

Once the file and thumbnail are uploaded successfully to the specified destination, the success message is shown

You may also like to read:

File upload examples

The output in the browser

When the upload form is shown to the user
thumbnail creation example in codeigniter

When user submits without selecting file
thumbnail creation example in codeigniter

When user selects a file and submit the form
thumbnail creation example in codeigniter

Directory Structure
thumbnail creation example in codeigniter

Create the table in the database

Here database name is cdcol and table is files. We will store file related information into this table but the actual file would be stored into a directory.

CREATE TABLE `files` (
  `file_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `file_name` varchar(255) COLLATE latin1_general_ci NOT NULL,
  `file_orig_name` varchar(255) COLLATE latin1_general_ci NOT NULL,
  `file_path` varchar(255) COLLATE latin1_general_ci NOT NULL,
  `upload_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`file_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci;

Go to application/config/database.php and change the value as per your database settings. This is required to establish connection with database otherwise we won’t be able to perform queries on database from codeigniter.

$db['default']['hostname'] = 'localhost';
$db['default']['username'] = 'root';
$db['default']['password'] = '';
$db['default']['database'] = 'cdcol';
$db['default']['dbdriver'] = 'mysql';

Go to application/config/autoload.php and change the value as shown below. We do not want to load everytime the repeatedly used libraries, helper functions etc, so it is always good to load those things in order to use them uniformly throughout the application.

$autoload['libraries'] = array('database');
$autoload['helper'] = array('url', 'file', 'text', 'form');

Create the view – upload form

As shown previously in the directory structure image, you have to create a form called file_upload.php under application/views/ folder.

In the below form I have used codigniter’s form helper tags. Also notice when we need to upload a file or files we have to use the enctype=”multipart/form-data” and hence we have used form_open_multipart().

If there is no need to upload a file then we can use only form_open(). We have passed some attributes, in form_open_multipart(), which will be added in the html’s form tag.

We have also some other variables like $errors, $success which will show errors and success messages respectively. We have codeigniter’s built-in validation_errors() function which will show also error messages.

<title>Welcome to CodeIgniter</title>
<style scoped="scoped" type="text/css">
body {
                background-color: #fff;
                margin: 40px;
                font: 13px/20px normal Helvetica, Arial, sans-serif;
                color: #4F5155;
            }
            #body{
                margin: 0 15px 0 15px;
            }
            #container{
                margin: 10px;
                border: 1px solid #D0D0D0;
                -webkit-box-shadow: 0 0 8px #D0D0D0;
            }
            .error {
                color: #E13300;
            }
            .info {
                color: gold;
            }
            .success {
                color: darkgreen;
            }
</style>
<div id="container">
<h1>File Upload Example</h1>
<div id="body">
<p>Select a file to upload</p>
<?php
                if (isset($success) && strlen($success)) {
                    echo '<div class="success">';
                    echo '<p>' . $success . '</p>';
                    echo '</div>';
                }
                if (isset($errors) && strlen($errors)) {
                    echo '<div class="error">';
                    echo '<p>' . $errors . '</p>';
                    echo '</div>';
                }
                if (validation_errors()) {
                    echo validation_errors('<div class="error">', '</div>');
                }
                ?>
<div><?php
                    $attributes = array('name' => 'file_upload_form', 'id' => 'file_upload_form');
                    echo form_open_multipart($this->uri->uri_string(), $attributes);
                    ?>
<p><input name="file_name" id="file_name" readonly="readonly" type="file" /></p>
<p><input name="file_upload" value="Upload" type="submit" /></p>
<?php
                    echo form_close();
                    ?></div>
</div>
</div>

File upload Controller

We have already default controller called welcome.php under application/controllers/. If you want you can also create your own controller. You can find the explanation in the comment for important statements.

This controller is responsible for thumbnail creation example in codeigniter.

In the below controller class we have loaded the required library to validate form.

We are handling error and success message through separate functions.

We have defined separate destination folders for uploading file and thumbnail.

We have set required configurations for file and thumbnail.

We are perform validations on file to check whether file was really uploaded or not.

<?php
if (!defined('BASEPATH'))
    exit('No direct script access allowed');
class Welcome extends CI_Controller {
    
    //variable for storing error message
    private $error;
    //variable for storing success message
    private $success;
    function __construct() {
        parent::__construct();
        //load this to validate the inputs in upload form
        $this->load->library('form_validation');
        //load this to transact with database
        $this->load->model('file_model', 'file');
    }
    //appends all error messages
    private function handle_error($err) {
        $this->error .= $err . "\r\n";
    }
    //appends all success messages
    private function handle_success($succ) {
        $this->success .= $succ . "\r\n";
    }
    //file upload action
    public function index() {
        //check whether submit button was clicked or not
        if ($this->input->post('file_upload')) {
            //set preferences
            
            //file upload destination
            $config['upload_path'] = './upload/';
            //allowed file types. * means all types
            $config['allowed_types'] = '*';
            //allowed max file size. 0 means unlimited file size
            $config['max_size'] = '0';
            /max file name size
            $config['max_filename'] = '255';
            //whether file name should be encrypted or not
            $config['encrypt_name'] = TRUE;
            
            //thumbnail path
            $thumb_path = './upload/thumb/';
            //store file info once uploaded
            $file_data = array();
            //check for errors
            $is_file_error = FALSE;
            //check if file was selected for upload
            if (!$_FILES) {
                $is_file_error = TRUE;
                $this->handle_error('Select at least one file.');
            }
            //if file was selected then proceed to upload
            if (!$is_file_error) {
                //load the preferences
                $this->load->library('upload', $config);
                //check file successfully uploaded. 'file_name' is the name of the input
                if (!$this->upload->do_upload('file_name')) {
                    //if file upload failed then catch the errors
                    $this->handle_error($this->upload->display_errors());
                    $is_file_error = TRUE;
                } else {
                    //store the file info
                    $file_data = $this->upload->data();
                    if (!is_file($thumb_path . $file_data['file_name'])) {
                        $config = array(
                            'source_image' => $file_data['full_path'], //get original image
                            'new_image' => $thumb_path,
                            'maintain_ratio' => true,
                            'width' => 150,
                            'height' => 100
                        );
                        $this->load->library('image_lib', $config); //load library
                        $this->image_lib->resize(); //do whatever specified in config
                    }
                }
            }
            // There were errors, we have to delete the uploaded files
            if ($is_file_error) {
                if ($file_data) {
                    $file = './upload/' . $file_data['file_name'];
                    if (file_exists($file)) {
                        unlink($file);
                    }
                    $thumb = $thumb_path . $file_data['file_name'];
                    if ($thumb) {
                        unlink($thumb);
                    }
                }
            }
            if (!$is_file_error) {
                //save the file info in the database
                $resp = $this->file->save_file_info($file_data);
                if ($resp === TRUE) {
                    $this->handle_success('File was successfully uploaded.');
                } else {
                    //if file info save in database was not successful then delete from the destination folder
                    $file = './upload/' . $file_data['file_name'];
                    if (file_exists($file)) {
                        unlink($file);
                    }
                    $thumb = $thumb_path . $file_data['file_name'];
                    if ($thumb) {
                        unlink($thumb);
                    }
                    $this->handle_error('Error while saving file info to Database.');
                }
            }
        }
        
        //load the error and success messages
        $data['errors'] = $this->error;
        $data['success'] = $this->success;
        //load the view along with data
        $this->load->view('file_upload', $data);
    }
}
/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */

The Model

This model class is responsible for interacting with the database and save the file info to the database.

As we said previously, we are using this table to store only file information but not the actual file. Actual file and thumbnail are uploaded into the directory on physical drive.

<?php
if (!defined('BASEPATH'))
    exit('No direct script access allowed');
/**
 * Description of file_model
 *
 * @author Admin
 */
class file_model extends CI_Model {
    //table name
    private $file = 'files';   // files
    function __construct() {
    }
    function save_file_info($file) {
        //start db traction
        $this->db->trans_start();
        //file data
        $file_data = array(
            'file_name' => $file['file_name'],
            'file_orig_name' => $file['orig_name'],
            'file_path' => $file['full_path'],
            'upload_date' => date('Y-m-d H:i:s')
        );
        //insert file data
        $this->db->insert($this->file, $file_data);
        //complete the transaction
        $this->db->trans_complete();
        //check transaction status
        if ($this->db->trans_status() === FALSE) {
            $file_path = $file['full_path'];
            //delete the file from destination
            if (file_exists($file_path)) {
                unlink($file_path);
            }
            //delete thumbnail image
            $thumb_path = './upload/thumb/';
            $thumb = $thumb_path . $file['file_name'];
            if ($thumb) {
                unlink($thumb);
            }
            //rollback transaction
            $this->db->trans_rollback();
            return FALSE;
        } else {
            //commit the transaction
            $this->db->trans_commit();
            return TRUE;
        }
    }
}
/* End of file file_model.php */
/* Location: ./models/file_model.php */

That’s all. Thanks for reading.

Hope you got idea on thumbnail creation example in codeigniter.

Tags:

I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger. Connect me on JEE Tutorials | TwitterFacebook Google PlusLinkedin | Reddit

Leave a Reply

Your email address will not be published. Required fields are marked *