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:
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 🙂
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
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.
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
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.
Hello, i’m going to try it out.
Thank you
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
i want to upload pdf file that have size 25 MB. How can i write code ?
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.
Is it possible for the files to be uploaded so we can see the code and how the file structure should be laid out.
HI I have uploaded pdf files success fully but i can’t able to display it so please help me?
Thanks in advance.
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 😀
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
Can you plz give a full project which was developed using Codeigniter ? It will help us to see the whole environment of Codeigniter.
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.
how can upload videos using php
Thanks. very useful
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..
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.
Works. Ty for share 😉
That code is not working can you please send me your email address so that I can send it for you correct me
Array
(
[file] => Array
(
[name] => vlc-record.mp4
[type] =>
[tmp_name] =>
[error] => 1
[size] => 0
)
)
i am getting the array like this while uploading video
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.
please tell me how to upload multiple images path on database
i can give you a code for codeigniter framework
if i have more then one input file. and name of the field. is- file[] then how to upload in uploads folder.
Does not work for multiple images
Hello every one
Do you know any one how to upload “.vtt” Webvtt file in CodeIgniter
hi i want to record the audio in my project any suggestion let me know..
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
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~