TUTORIAL

Cara membuat validasi upload file atau gambar di Codeigniter

シックス , TUTORIAL
0
15146

CodeIgniter menyediakan kelas validasi form yang membantu untuk memvalidasi filed form dengan kode yang sedikit. Umumnya, kita menggunakan rule required dalam CodeIgniter untuk memvalidasi field form. But rule required tidak akan bisa bekerja ketika kita mencoba untuk memvalidasi file upload. Didalam tutorial ini kita akan belajar bagaimana untuk menambah validasi untuk mengupload file dalam CodeIgniter.

For better understanding, we’ll demonstrate the complete file upload process with file upload validation. Using our example code you can implement file or image upload functionality with file input field validation in CodeIgniter.

 

Berikut gambaran struktur folder dan file untuk membuat validasi upload di Codeigniter:

 

codeigniter-file-upload-validation-files-structure-codexworld

 

Upload Directory

Anda perlu membuat sebuah direktori untuk menyimpan file upload. Sebagai contoh uploads/files/directory.

 

Controller (Files.php)

File controller berisi 2 fungsi, upload() and file_check().

 

Fungsi upload() menangani fungsi berikut.

  1. Load Form file upload.
  2. Memvalidasi field file input dan mengecek isi field dan type atau format file.
  3. Mengupload file ke server.

 

Berkut built-in CodeIgniter library and helper yang digunakan untuk meng-upload file dengan validasi di CodeIgniter.

  1. form_validation – Memvalidasi fields dalam form.
  2. file – Menyediakan fungsi get_mime_by_extension() untuk membaca format ekstensi dari file yang diuploaded.
  3. upload – Mengupload file ke server.

file_check() adalah fungsi validasi untuk memeriksa apakah  file input kosong atau file yang dipilih tidak diperbolehkan.

 


<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * Files management class created by CodexWorld
 */
class Files extends CI_Controller {
    
    function __construct() {
        parent::__construct();
    }
    
    public function upload(){
        $data = array();
        
        //load form validation library
        $this->load->library('form_validation');
        
        //load file helper
        $this->load->helper('file');
        
        if($this->input->post('uploadFile')){
            $this->form_validation->set_rules('file', '', 'callback_file_check');

            if($this->form_validation->run() == true){
                //upload configuration
                $config['upload_path']   = 'uploads/files/';
                $config['allowed_types'] = 'gif|jpg|png|pdf';
                $config['max_size']      = 1024;
                $this->load->library('upload', $config);
                //upload file to directory
                if($this->upload->do_upload('file')){
                    $uploadData = $this->upload->data();
                    $uploadedFile = $uploadData['file_name'];
                    
                    /*
                     *insert file information into the database
                     *.......
                     */
                    
                    $data['success_msg'] = 'File has been uploaded successfully.';
                }else{
                    $data['error_msg'] = $this->upload->display_errors();
                }
            }
        }
        
        //load the view
        $this->load->view('files/upload', $data);
    }
    
    /*
     * file value and type check during validation
     */
    public function file_check($str){
        $allowed_mime_type_arr = array('application/pdf','image/gif','image/jpeg','image/pjpeg','image/png','image/x-png');
        $mime = get_mime_by_extension($_FILES['file']['name']);
        if(isset($_FILES['file']['name']) && $_FILES['file']['name']!=""){
            if(in_array($mime, $allowed_mime_type_arr)){
                return true;
            }else{
                $this->form_validation->set_message('file_check', 'Please select only pdf/gif/jpg/png file.');
                return false;
            }
        }else{
            $this->form_validation->set_message('file_check', 'Please choose a file to upload.');
            return false;
        }
    }
}

 

View (files/upload.php)


<?php 
    if(!empty($success_msg)){
        echo '<p class="statusMsg">'.$success_msg.'</p>';
    }elseif(!empty($error_msg)){
        echo '<p class="statusMsg">'.$error_msg.'</p>';
    }
?>

<form method="post" enctype="multipart/form-data">
    <p><input type="file" name="file"/></p>
    <?php echo form_error('file','<p class="help-block">','</p>'); ?>
    <p><input type="submit" name="uploadFile" value="UPLOAD"/></p>
</form>

 

Berikut link Live demo dan sourcecode.

 

LIVE DEMO    DOWNLOAD SOURCE CODE

 

Sekian tutorial kali ini, semoga dapat mambantu pekerjaan anda.

0 Comments

×