File upload functionality is one of the most common requirements for most web applications. If we go for raw implementation, we would need to do some basic initialization manually, which makes the code redundant and time-consuming. This risks having buggy code. To recover from these issues and make our development life easier, the Codeigniter framework provides a decent and efficient way to do this. The Codeigniter file upload library is very simple to use and configurable. I will show a very basic implementation of this tutorial, which should help beginners adapt to this library quickly.
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.
First, we need to prepare a simple form view. This will be used for rendering the HTML to the user to allow file upload functionality. A simple HTML form with file upload support would be as follows:
We have used ‘enctype’ attribute (which 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 central control where the user will be able to select a file from his local computer. By default, the user will be able to select a 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 nicely.
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 defined by the 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. You will need to initialize separate configurations if your web application has different forms to upload files with different criteria. Here is a basic configuration file structure. You should keep it in ‘application/config’ directory and load it when needed. Otherwise, you can keep it in your controller/library function also, depending on your application’s architecture:
You just need to be careful when setting these because errors may occur if we set this wrong. You will find that this is the most important part of the functionality.
CodeIgniter File Upload Library In Action:
After we have defined the configuration correctly, our task is straightforward. We will load the ‘upload’ library and call the ‘do_upload’ method. The code will be as follows inside your Codeigniter controller:
If an error occurs, you can show the messages that are 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 in detail in the demo example)
After a successful file upload demo exercise (as on the link below), you should see the result as follows:
Uploading ZIP Files:
Uploading a zip file is similar to other types of files. However, you may face a little problem, as on the 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:
As you can see, all other mime types are checked against the file upload operation of that type and can be ignored if the correct types don’t exist. So keep your eye open while implementing the Codeigniter file upload operation.
Check Upload Configuration: Also, don’t forget to add these types on your upload configuration’s allowed types:
Now you should be doing fine. Let me know if you still face problems with the zip file upload.
Essential Factors To Consider:
File/Directory Permission: You must ensure that PHP has proper write permission on those directories where you want the uploaded file to be saved. Generally, a ‘755’ or ‘777’ permission works fine.
Script Timeout Settings: If your application allows the big-size file to be uploaded, you need to ensure that your server’s PHP configuration allows enough time before resulting in a timeout error for file upload.
Proper Settings: Though I mentioned once already, again to say, proper settings are necessary. You need to understand and set them carefully. Such as, in the above example, we have used ‘max_height’ and ‘max_width’ properties, which are mainly for image-type files. So, if your application doesn’t allow image upload, you don’t need to use them.
I hope this simple tutorial will help you get started with using the CodeIgniter file upload functionality. If you have a problem or have a question, feel free to ask me. Happy coding 🙂
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.
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();
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.
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’.
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.
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 😀
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
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.
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.
var JetpackInstantSearchOptions=JSON.parse(decodeURIComponent("%7B%22overlayOptions%22%3A%7B%22colorTheme%22%3A%22light%22%2C%22enableInfScroll%22%3Atrue%2C%22enableFilteringOpensOverlay%22%3Atrue%2C%22enablePostDate%22%3Atrue%2C%22enableSort%22%3Atrue%2C%22highlightColor%22%3A%22%23FFC%22%2C%22overlayTrigger%22%3A%22submit%22%2C%22resultFormat%22%3A%22expanded%22%2C%22showPoweredBy%22%3Atrue%2C%22defaultSort%22%3A%22relevance%22%2C%22excludedPostTypes%22%3A%5B%5D%7D%2C%22homeUrl%22%3A%22https%3A%5C%2F%5C%2Fcodesamplez.com%22%2C%22locale%22%3A%22en-US%22%2C%22postsPerPage%22%3A5%2C%22siteId%22%3A18994550%2C%22postTypes%22%3A%7B%22post%22%3A%7B%22singular_name%22%3A%22Post%22%2C%22name%22%3A%22Posts%22%7D%2C%22page%22%3A%7B%22singular_name%22%3A%22Page%22%2C%22name%22%3A%22Pages%22%7D%2C%22attachment%22%3A%7B%22singular_name%22%3A%22Media%22%2C%22name%22%3A%22Media%22%7D%7D%2C%22webpackPublicPath%22%3A%22https%3A%5C%2F%5C%2Fcodesamplez.com%5C%2Fwp-content%5C%2Fplugins%5C%2Fjetpack%5C%2Fjetpack_vendor%5C%2Fautomattic%5C%2Fjetpack-search%5C%2Fbuild%5C%2Finstant-search%5C%2F%22%2C%22isPhotonEnabled%22%3Afalse%2C%22isFreePlan%22%3Atrue%2C%22apiRoot%22%3A%22https%3A%5C%2F%5C%2Fcodesamplez.com%5C%2Fwp-json%5C%2F%22%2C%22apiNonce%22%3A%22155bc22a78%22%2C%22isPrivateSite%22%3Afalse%2C%22isWpcom%22%3Afalse%2C%22hasOverlayWidgets%22%3Afalse%2C%22widgets%22%3A%5B%5D%2C%22widgetsOutsideOverlay%22%3A%5B%5D%2C%22hasNonSearchWidgets%22%3Afalse%2C%22preventTrackingCookiesReset%22%3Afalse%7D"));
carlarrj says
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
Md Ali Ahsan Rana says
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.
carlarrj says
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
Md Ali Ahsan Rana says
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.
carlarrj says
Hello, i’m going to try it out.
Thank you
karabo says
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
construction-property.com says
i want to upload pdf file that have size 25 MB. How can i write code ?
Md Ali Ahsan Rana says
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.
Adam says
Is it possible for the files to be uploaded so we can see the code and how the file structure should be laid out.
ganga says
HI I have uploaded pdf files success fully but i can’t able to display it so please help me?
Thanks in advance.
freddy sidauruk says
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 😀
surya pratap singh says
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
Ahbab says
Can you plz give a full project which was developed using Codeigniter ? It will help us to see the whole environment of Codeigniter.
Md Ali Ahsan Rana says
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.
rohit says
how can upload videos using php
bhumishah says
Thanks. very useful
Ajay says
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..
Noman Ibrahim says
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.
rinnzleer says
Works. Ty for share 😉
bmadire4 says
That code is not working can you please send me your email address so that I can send it for you correct me
sandeep says
Array
(
[file] => Array
(
[name] => vlc-record.mp4
[type] =>
[tmp_name] =>
[error] => 1
[size] => 0
)
)
i am getting the array like this while uploading video
rakesh ranjan says
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.
Anjana says
please tell me how to upload multiple images path on database
shashank says
i can give you a code for codeigniter framework
Devendra Chauhan says
if i have more then one input file. and name of the field. is- file[] then how to upload in uploads folder.
Toto Prayogo says
Does not work for multiple images
tarun says
Hello every one
Do you know any one how to upload “.vtt” Webvtt file in CodeIgniter
Perumal Bs says
hi i want to record the audio in my project any suggestion let me know..
mahadevan says
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
Chin Cong says
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~