Thursday, November 12, 2009

Codeigniter Guide File Uploading Class


Codeigniter's Uploading Class lets people upload any type of file as long as it is set as allowed type to upload.



$config['allowed_types'] = 'jpg|png|gif';
Official Documentation: CodeIgniter User Guide Version 1.7.2 File Uploading Class

In my case, I tried to upload an excel file (.xls), so I set the allowed type to xls.



$config['allowed_types'] = 'xls'; But it returns an error The filetype you are attempting to upload is not allowed. So I tried to create my uploading class and it extends to CI_Upload class.
./application/libraries/MY_Upload.php


<?php if (!defined('BASEPATH')) exit('No direct script access allowed'); class MY_Upload extends CI_Upload { function __construct($props = array()) { parent::CI_Upload($props); } /** * Verify that the filetype is allowed * * @access public * @return bool */ public function is_allowed_filetype() { if (count($this->allowed_types) == 0 OR ! is_array($this->allowed_types)) { $this->set_error('upload_no_file_types'); return FALSE; } $image_types = array('gif', 'jpg', 'jpeg', 'png', 'jpe'); foreach ($this->allowed_types as $val) { $mime = $this->mimes_types(strtolower($val)); // Images get some additional checks if (in_array($val, $image_types)) { if (getimagesize($this->file_temp) === FALSE) { return FALSE; } } if (is_array($mime)) { if (in_array($this->file_type, $mime, TRUE)) { return TRUE; } } else { if ($mime == $this->file_type) { return TRUE; } } // Last option compare the .ext file with allowed_types if(is_array($this->allowed_types)) { if(in_array($val, $this->allowed_types)) { return TRUE; } } elseif($this->allowed_types == $val) { return TRUE; } } return FALSE; } } /* End of file MY_Upload.php */ /* Location: ./application/library/MY_Upload.php */


No comments:

Post a Comment