Upload dan Extrac File Zip Dengan Codeigniter – Dalam posting ini saya akan menjelaskan cara Upload dan Extract file zip menggunakan library upload file codeigniter dan library PHP Zipachive. Mari kita mulai dengan membuat File codeigniter yang diperlukan (controller dan view).
Pertama, Buat file view untuk mengupload file, upload_form_view.php dalam tampilan {applications/views/upload_form_view.php}
1 2 3 4 5 6 7 8 9 10 11 12 13 | <html> <head> <title>Upload Form</title> </head> <body> <?php echo isset($error) ? $error : ''; ?> <?php echo form_open_multipart('upload/file_upload');?> <input type="file" name="userfile" size="20" /> <br /><br /> <input type="submit" value="upload" /> </form> </body> </html> |
Kemudian buat file view untuk menampilkan Pesan Sukses dan file yang diupload, upload_success_view.php dalam tampilan {applications/views/upload_success_view.php}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <html> <head> <title>Upload Form</title> </head> <body> <h3>Your file was successfully uploaded!</h3> <ul> <?php foreach ($upload_data as $item => $value):?> <li><?php echo $item;?>: <?php echo $value;?></li> <?php endforeach; ?> </ul> <p><?php echo anchor('upload', 'Upload Another File!'); ?></p> </body> </html> |
Kemudian buat controller dengan nama upload.php di controllers (applications/controller/upload.php)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | Class Upload extends CI_Controller { function __construct() { parent::__construct(); // memanggil helper form dan url $this->load->helper(array('form', 'url')); } function index() { $this->load->view('upload_form_view', array('error' => ' ' )); } function file_upload() { $config['upload_path'] = './uploads/'; $config['allowed_types'] = 'zip'; $config['max_size'] = ''; $this->load->library('upload', $config); if ( ! $this->upload->do_upload()) { $error = array('error' => $this->upload->display_errors()); $this->load->view('upload_form_view', $error); } else { $data = array('upload_data' => $this->upload->data()); $zip = new ZipArchive; $file = $data['upload_data']['full_path']; chmod($file,0777); if ($zip->open($file) === TRUE) { $zip->extractTo('./uploads/'); $zip->close(); echo 'ok'; } else { echo 'failed'; } $this->load->view('upload_success_view', $data); } } } |
Catatan:
1. Ekstensi PHP Zip Archieve dapat digunakan untuk mengekstrak file zip. Izinkan/aktifkan ekstensi ini di php.ini jika tidak diaktifkan secara default.
2. Buat Folder upload di direktori Root aplikasi