CodeSamplez.com

Programming, Web development, Cloud Technologies

  • Facebook
  • Google+
  • RSS
  • Twitter
  • Home
  • Featured
    • C# Tutorials
      • LinQ Tutorials
      • Facebook C# API Tutorials
    • PHP Tutorials
      • CodeIgniter Tutorials
    • Amazon AWS Tutorials
  • Categories
    • Programming
    • Development
    • Database
    • Web Server
    • Source Control
    • Management
    • Project
  • About
  • Write
  • Contact
Home Development Tutorial On Uploading File With CodeIgniter Framework / PHP

Tutorial On Uploading File With CodeIgniter Framework / PHP

Rana Ahsan March 11, 2013 30 Comments


 Tutorial On Uploading File With CodeIgniter Framework / PHP    

File upload functionality is one of the most common requirements for most of the web applications. If we go for raw implementation, we would need to do some basic initialization manually. Which make the code redundant, time-consuming and conduct the risk of having buggy code. To recover from these issues and make our development life easier, Codeigniter framework provides a descent and efficient way to do this. Codeigniter file upload library is a very simple to use and configurable. I will show a very basic implementation on this tutorial, that should help beginners to adapt with this library easily.

I am assuming you have used codeigniter more or less. If you are a complete beginner with Codeigniter, you should pursue some basic codeigniter knowledge with model/view/controller usage.

Read The Complete CodeIgniter Tutorials Series By CodeSamplez.com

Prepare the view:

First, we need to prepare a simple form view. This will be used for rendering the html to user for allowing file upload functionality. A simple HTML form with file upload support would be as follows:

<form action="" method="POST" enctype="multipart/form-data" >
    Select File To Upload:<br />
    <input type="file" name="userfile"  />
    <br /><br />
    <input type="submit" name="submit" value="Upload" class="btn btn-success" />
</form>

notice few things on the above code example:

  • We have used ‘enctype’ attribute (means ‘ENCode Type’) with a value of “multipart/form-data” in ‘form’ tag, which tells that, this form will contain a file upload control. you can check more about this enctype attribute on w3schools.
  • A file browser control is added by specifying type=’file’. This is the main control where user will be able to select a file from his local computer. By default user will be able to select single file. But if you wish to facilitate multiple files on your web application, you can additionally use “multiple=’multiple'” attribute in this tag. This will do the trick well.

Define A Configuration For Uploaded File:

Let us move to our server-side PHP codes. First , we will need to make a configuration array. This is an associative array, which is defined by codeigniter file upload library for certain keys. This will include the basic settings for file upload like upload path, maximum size, allowed file types etc. If your web application has different forms to upload files with different criteria, you will need to initialize separate configuration for them. Here is a basic configuration file structure, you should keep it in ‘application/config’ directory and load when needed, otherwise you can keep it in your controller/library function also, depending on your application’s architecture:

$this->config =  array(
                  'upload_path'     => dirname($_SERVER["SCRIPT_FILENAME"])."/files/",
                  'upload_url'      => base_url()."files/",
                  'allowed_types'   => "gif|jpg|png|jpeg|pdf|doc|xml",
                  'overwrite'       => TRUE,
                  'max_size'        => "1000KB",
                  'max_height'      => "768",
                  'max_width'       => "1024"   
                );

you must need to be careful when setting these, because if we set this wrong, errors may occur. You will find that, this is the actually most important part in the functionality.

CodeIgniter File Upload Library In Action:

After we have defined the configuration properly our task is very simple. We will just load the ‘upload’ library and call the ‘do_upload’ method. Code will be as follows inside your codeigniter controller:

$this->load->library('upload', $this->config);
if($this->upload->do_upload())
{
    echo "file upload success";
}
else
{
   echo "file upload failed";
}

If error occurs, you can show the messages that is generated by codeigniter itself, mentioning the main reason by using “display_errors()” function of the library. Also, after a successful upload, you can use various properties of the uploaded file from the object returned by this library’s ‘data()’ method. (This is demonstrated details on demo example)

After a successful file upload demo exercise (as on link below), you should see a result as follows:

codeigniter file upload tutorial


Checkout The CodeIngiter File Upload Demo!

Uploading ZIP Files:

Uploading zip file is similar like other types of files. But you may face a little problem as on current latest codeigniter version(2.1.3), not all mime types are declared. Follow the below steps to get it working if you are having issues:

  • Add more mime types: In your application/config/mimes.php file, add/edit the following types:
    'zip'	=>  array('application/zip', 'application/x-zip', 'application/x-zip-compressed', 'application/octet-stream', 'application/x-compress', 'application/x-compressed', 'multipart/x-zip'),
    				'rar'   => array('application/rar', 'application/x-rar', 'application/x-rar-compressed', 'application/x-compressed', 'application/octet-stream'),
    

    As you can see all other mime types, they are checked against while file upload operation of that type and can be ignored if correct types aren’t exists. So keep your eye open while implementing codeigniter file upload operation.

  • Check Upload Configuration: Also don’t forget to add these types on your upload configuration’s allowed types:
    'allowed_types'   => "gif|jpg|png|jpeg|pdf|doc|xml|zip|rar",
    

Now you should be doing fine. Let me know if you are still facing problems in zip file upload.

Important Factors To Consider:

  • File/Directory Permission: You must need to make sure that, where you want the uploaded file to be saved, php has proper write permission on those directories. Generally a ‘755’ or ‘777’ permission works fine.
  • Script Timeout Settings: If your application allow big size file to be uploaded, then you must need to make sure that, your server’s PHP configuration allow enough time before resulting a timeout error for file upload.
  • Proper Settings: Though I mentioned once already, again to say, a proper settings is necessary. You need to understand and set them carefully. Such as, on the above example we have used ‘max_height’ and ‘max_width’ property, which are mainly for image type file. So, if your application doesn’t allow image upload, you don’t need to use them.

Further References:

You should also read the official codeigniter documentation guide for file upload class to know n depth of the configuration details. It also provides detail information of the uploaded file, that codeigniter preserves as well.

Hope this simple tutorial will help you get started with using codeigniter file upload functionality. If you are having problem or have a question, feel free to ask me about it. Happy coding ๐Ÿ™‚

Related

Filed Under: Development Tagged With: codeigniter, php

About Rana Ahsan

Rana is a passionate software engineer/Technology Enthusiast.
Github: ranacseruet

Comments

  1. carlarrj says

    June 14, 2013 at 8:59 am

    Hello, i’m trying using your code to upload one file to the server but i’m facing some problems, could you please help me out?

    Thanks in advance

    Reply
    • Md Ali Ahsan Rana says

      June 14, 2013 at 9:03 am

      Sure, what kind of issue you are facing? Please Mention details and if possbile, share your code on http://pastebin.com/ or similar place and give me link. Thanks.

      Reply
  2. carlarrj says

    June 14, 2013 at 9:24 am

    Hello,

    Thanks for the quick reply. I’m a newbie and i’m using the upload script in http://www.timprexe.com/en/contatos/ but i’m having this error:
    Message: Undefined property: CI::$uploader
    Filename: MX/Controller.php
    Line Number: 58

    Just a few moments ago i get hover this error when i changed:
    $this->load->library(“uploader”);
    $this->uploader->do_upload();

    to

    $this->load->library(“upload”);
    $this->upload->do_upload();

    but couldn’t make the upload of the file and i just started again.

    Could you please help me? I have the uploader.php inside application\config http://pastebin.com/ehfZmq6X this is my controller http://pastebin.com/qZrZRV99 and this is my view http://pastebin.com/Vfv6LK4H

    Thanks in advance

    Reply
    • Md Ali Ahsan Rana says

      June 14, 2013 at 9:45 am

      OK, first thing, your first code snippet was right according to my demo example. On later one, you just loaded the CI uploader instead of our custom uploader library, but didn’t perform other operations such as $config etc. Thus, its not working.

      My first suggestion will be to figure out why your can’t load the library ‘uploader’.

      I am assuming you have this “uploader.php” on your application/libraries directory, am I right? or is it in some subdirectory? Like if you have the library in “application/libraries/app/uploader.php” then, you should use “$this->load->library(‘app/uploader’)”;

      Also, is your development environment ‘case sensitive’? If so, it may looking for “Uploader.php” instead of “uploader.php”. so, make the change, name the file with upper case ‘U’ and try.

      If still facing error, let me know. Thanks.

      Reply
  3. carlarrj says

    June 14, 2013 at 9:57 am

    Hello, i’m going to try it out.

    Thank you

    Reply
  4. karabo says

    January 23, 2014 at 10:04 am

    Good Day

    Am trying out your tutorial. Am experiencing a problem with placing the config array in the the controller. I have a fill named upload.php, please give me an example where to upload the ‘config array’.

    Thanks for the tutorial

    Reply
  5. construction-property.com says

    March 4, 2014 at 8:59 pm

    i want to upload pdf file that have size 25 MB. How can i write code ?

    Reply
    • Md Ali Ahsan Rana says

      March 5, 2014 at 3:05 am

      Please change the php.ini for ‘upload_max_filesize = 25M’ and ‘post_max_size = 25M’ settings. Then, also change the upload config’s ‘max_size’ settings and make sure ‘allowed_types’ have ‘pdf’ type. Then you should be OK to go. Let me know if you still have any issue.

      Reply
  6. Adam says

    September 9, 2014 at 6:04 am

    Is it possible for the files to be uploaded so we can see the code and how the file structure should be laid out.

    Reply
  7. ganga says

    September 23, 2014 at 1:01 am

    HI I have uploaded pdf files success fully but i can’t able to display it so please help me?
    Thanks in advance.

    Reply
  8. freddy sidauruk says

    October 21, 2014 at 5:29 am

    can you give me tutorial with database ?

    i request just simple image with database, if you have time cause i’m new bie at Codeigniter, please inform me at sidaurukfreddy@gmail.com sorry if it’s not polite ๐Ÿ˜€

    Reply
  9. surya pratap singh says

    November 30, 2014 at 4:46 am

    hello
    i am new in codeigniter so i want to upload image in these location
    upload->year->month->day
    if these folder already exixt so upload image if doesnt create and upload
    and last thing i want also sent id title and image path to data base
    i do lot of thing but not working is any one create
    view,controller and model

    Reply
  10. Ahbab says

    December 31, 2014 at 4:09 pm

    Can you plz give a full project which was developed using Codeigniter ? It will help us to see the whole environment of Codeigniter.

    Reply
    • Md Ali Ahsan Rana says

      December 31, 2014 at 5:45 pm

      Sorry buddy, can’t share with you. However, you can check my ‘codeigniterplus’ open source project, which will give you some more grasp/idea: https://github.com/ranacseruet/codeigniterplus . All demos on this sites are prepared on the top of this.

      Reply
  11. rohit says

    February 14, 2015 at 7:15 am

    how can upload videos using php

    Reply
  12. bhumishah says

    March 5, 2015 at 4:22 am

    Thanks. very useful

    Reply
  13. Ajay says

    April 2, 2015 at 11:57 am

    Severity: Warning

    Message: pg_query(): Query failed: ERROR: null value in column “ImageNameWithExtension” violates not-null constraint DETAIL: Failing row contains (L , 16th, null, 12, 120, test, tsseet, test, test, 2015-04-02 18:53:18+05:30, 2015-04-02 18:53:18+05:30, 1, 894, 1).

    Filename: postgre/postgre_driver.php

    Line Number: 246

    Backtrace:

    File: C:\xampp\htdocs\iloksabha\application\models\Digitalasset_modal.php
    Line: 35
    Function: insert

    File: C:\xampp\htdocs\iloksabha\application\controllers\Digitalasset.php
    Line: 67
    Function: set_value

    File: C:\xampp\htdocs\iloksabha\index.php
    Line: 292
    Function: require_once

    please solution me..

    Reply
  14. Noman Ibrahim says

    December 6, 2015 at 12:49 pm

    It was a nightmare following this tut for image uploading…. I hate official documentations but some times they are true life saver.
    Thanks btw Rana Sahb.

    Reply
  15. rinnzleer says

    January 2, 2016 at 2:51 pm

    Works. Ty for share ๐Ÿ˜‰

    Reply
  16. bmadire4 says

    January 27, 2016 at 8:39 am

    That code is not working can you please send me your email address so that I can send it for you correct me

    Reply
  17. sandeep says

    May 11, 2016 at 10:41 am

    Array
    (
    [file] => Array
    (
    [name] => vlc-record.mp4
    [type] =>
    [tmp_name] =>
    [error] => 1
    [size] => 0
    )

    )

    i am getting the array like this while uploading video

    Reply
  18. rakesh ranjan says

    June 25, 2016 at 1:00 am

    Dear writer i want to upload image in directory and save the path of image in database and i want to retrieve on another page can you help me please.

    Thanks in advance.

    Reply
  19. Anjana says

    October 3, 2016 at 7:27 am

    please tell me how to upload multiple images path on database

    Reply
    • shashank says

      March 14, 2017 at 11:36 pm

      i can give you a code for codeigniter framework

      Reply
  20. Devendra Chauhan says

    October 21, 2016 at 7:21 am

    if i have more then one input file. and name of the field. is- file[] then how to upload in uploads folder.

    Reply
  21. Toto Prayogo says

    January 11, 2017 at 3:42 am

    Does not work for multiple images

    Reply
  22. tarun says

    February 6, 2017 at 8:48 am

    Hello every one

    Do you know any one how to upload “.vtt” Webvtt file in CodeIgniter

    Reply
  23. Perumal Bs says

    March 20, 2017 at 7:27 am

    hi i want to record the audio in my project any suggestion let me know..

    Reply
  24. mahadevan says

    June 30, 2017 at 3:34 am

    hai sir
    i have some problem in codeigniter
    i used one data from one table and then data to change some to store another table how to do it

    Reply
  25. Chin Cong says

    December 28, 2017 at 3:58 am

    Hi sir
    I read your helps carefully.
    I also have a problem.

    <form action="Admin_con/verbose_upload” method=”POST” enctype=”multipart/form-data”>

    Adding Animal

    Name:

    Category:

    Image:

    Model:

    Latitude:

    Longitude:

    And in controller, Admin_con/verbose_upload method is…

    public function verbose_upload()
    {
    $this->config = array(
    ‘upload_path’ => dirname($_SERVER[“SCRIPT_FILENAME”]).”/files/”,
    ‘upload_url’ => base_url().”files/”,
    ‘allowed_types’ => “*”,
    ‘overwrite’ => TRUE,
    ‘max_size’ => “10000KB”
    );
    $this->load->library(‘upload’, $this->config);
    if($this->upload->do_upload())
    {
    echo “file upload success”;
    }
    else
    {
    echo “file upload fail”;
    }
    }

    But result is

    file upload fail

    I dont know what ‘s the matter.
    I will wait your help.
    Best Regards~

    Reply

Leave a Reply Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Email Subscription

Never miss any programming tutorial again.

Popular Tutorials

  • How To Work With JSON In Node.js / JavaScript
  • PHP HTML5 Video Streaming Tutorial
  • How To Work With C# Serial Port Communication
  • LinQ Query With Like Operator
  • Facebook C# API Tutorials
  • LinQ To SQL Database Update Operations In C#
  • Using Supervisord Web Interface And Plugin
  • Tutorial On Uploading File With CodeIgniter Framework / PHP
  • Utilizing Config File In C#.NET Application
  • Getting Started With Smarty Template Engine

Recent Tutorials

  • Building Auth With JWT – Part 1
  • Document Your REST API Like A Pro
  • Understanding Golang Error Handling
  • Web Application Case Studies You Must Read
  • Getting Started With Golang Unit Testing
  • Getting Started With Big Data Analytics Pipeline
  • NodeJS Tips And Tricks For Beginners
  • Apple Push Notification Backend In NodeJS
  • Web Based Universal Language Translator, Voice/Text Messaging App
  • How To Dockerize A Multi-Container App From Scratch

Recent Comments

  • S. Chalisque on PHP HTML5 Video Streaming Tutorial
  • Armorik on Generate HTTP Requests using c#
  • iswaps on PHP HTML5 Video Streaming Tutorial
  • TAKONDWA on PHP HTML5 Video Streaming Tutorial
  • rorenzo on PHP HTML5 Video Streaming Tutorial

Archives

Resources

  • CodeSamplez.com Demo

Tags

.net apache api audio aws c# cache cloud server codeigniter deployment doctrine facebook git github golang htaccess html5 http image java javascript linq mysql nodejs oop performance php phpmyadmin plugin process python regular expression scalability server smarty ssh tfs thread tips ubuntu unit-test utility web application wordpress wpf

Copyright © 2010 - 2022 · CodeSamplez.com ·

Copyright © 2022 ยท Streamline Pro Theme on Genesis Framework ยท WordPress ยท Log in