CodeIgniter File Upload Tutorial Demo:

This small demo will show you how the codeigniter file upload tutorial would work in real time implementation. Here in this example demo, you will be able to upload a single file at a time with file type restricted to gif,jpg,png,jpeg,pdf,doc and xml . After a file uploaded successfully, you should be able to see the details of the uploaded file that codeigniter preserve in its internal variable.

Select File To Upload:




Back To The CodeIgniter File Upload Tutorial Page

Controller Function Code:
  1. /**
  2. * the demo for file upload tutorial on codesamplez.com
  3. * @return view
  4. */
  5. public function file_upload_demo()
  6. {
  7. try
  8. {
  9. if($this->input->post("submit")){
  10. $this->load->library("app/uploader");
  11. $this->uploader->do_upload();
  12. }
  13. return $this->view();
  14. }
  15. catch(Exception $err)
  16. {
  17. log_message("error",$err->getMessage());
  18. return show_error($err->getMessage());
  19. }
  20. }
Smarty Template View Code:
  1. <form action="" method="POST" enctype="multipart/form-data" >
  2. Select File To Upload:<br />
  3. <input type="file" name="userfile" multiple="multiple" />
  4. <input type="submit" name="submit" value="Upload" class="btn btn-success" />
  5. </form>
  6.  
  7. {if isset($uploaded_file)}
  8. {foreach from=$uploaded_file key=name item=value}
  9. {$name} : {$value}
  10. <br />
  11. {/foreach}
  12. {/if}
our application's 'uploader' library Code:
  1. /**
  2. * Description of uploader
  3. *
  4. * @author Rana
  5. */
  6. class Uploader {
  7. var $config;
  8. public function __construct() {
  9. $this->ci =& get_instance();
  10. $this->config = array(
  11. 'upload_path' => dirname($_SERVER["SCRIPT_FILENAME"])."/files/",
  12. 'upload_url' => base_url()."files/",
  13. 'allowed_types' => "gif|jpg|png|jpeg|pdf|doc|xml",
  14. 'overwrite' => TRUE,
  15. 'max_size' => "1000KB",
  16. 'max_height' => "768",
  17. 'max_width' => "1024"
  18. );
  19. }
  20. public function do_upload(){
  21. $this->remove_dir($this->config["upload_path"], false);
  22. $this->ci->load->library('upload', $this->config);
  23. if($this->ci->upload->do_upload())
  24. {
  25. $this->ci->data['status']->message = "File Uploaded Successfully";
  26. $this->ci->data['status']->success = TRUE;
  27. $this->ci->data["uploaded_file"] = $this->ci->upload->data();
  28. }
  29. else
  30. {
  31. $this->ci->data['status']->message = $this->ci->upload->display_errors();
  32. $this->ci->data['status']->success = FALSE;
  33. }
  34. }
  35. function remove_dir($dir, $DeleteMe) {
  36. if(!$dh = @opendir($dir)) return;
  37. while (false !== ($obj = readdir($dh))) {
  38. if($obj=='.' || $obj=='..') continue;
  39. if (!@unlink($dir.'/'.$obj)) $this->remove_dir($dir.'/'.$obj, true);
  40. }
  41.  
  42. closedir($dh);
  43. if ($DeleteMe){
  44. @rmdir($dir);
  45. }
  46. }
  47. }
  48.