Allow All File Type Uploads in CodeIgniter

File uploads in CodeIgniter need permissions to initialize upload class and then defined file types. Defining multiple  number of file type extension is a lengthy work using set_allowed_types. We will implement all file types upload  in code igniter and extend the CI_Upload class . Learn how to Allow all File Types Uploads in CodeIgniter.
Set file types is main factor for uploading a file otherwise. File upload you stop working &  an error appear "You have not specified any allowed file types".

Default File Upload in CodeIgniter:

  • Load codeigniter upload library in your controller using $this->load->library('upload').
  • Use set_allowed_types to define which files are allowed to upload.
$this->load->library('upload');
$this->upload->set_allowed_types('jpg|jpeg|gif|png|zip');
Above lines will allow file time jpg, jpeg, gif, png, zip. Other files extensions can be added separated by "|" bar.

Allow All File Type in CodeIgniter:

Upload Class tutorial will lead you to extended CI_Upload class . Upload any type of file and media in your codeigniter.
  • Make a library with a name of My_Upload.php .
  • Go to your application folder > Libraries > My_Upload.php (not exists create it) .
  • Paste the below code to upload any type of media in code igniter.
class MY_Upload extends CI_Upload {
 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;
 }
if (in_array("*", $this->allowed_types)) {
 return TRUE;
}
$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;
 }
}
}
 return FALSE;
}
}

Upload any File - Codeigniter

Extending the class CI_Upload makes you eligible to use  * to allow any file type.
$this->load->library('upload');
$this->upload->set_allowed_types('*');
  • Call the upload library first by using this->load->library('upload').
  • set allowed type to * will make any file upload in codeigniter

Precautions of File Upload - Codeigniter:

Hope you can now implement your code and can allow your application to allow any file in media. We suggest you to be aware of live applications hope you will save yourself from hack*ing.
In house organizations can implement such type of code to better run their application. Professional way is to define every single extension to avoid any future problem.

Post a Comment

0 Comments