This tutorial will show how to upload file in CodeIgniter using File Uploading Class. CodeIgniter’s File Uploading Class helps to upload files to the server. You can use various preferences for configuring your file upload and restrict the type and size of the files. For your better understand we’ll demonstrate the file upload with an example. Also, we’ll upload the user picture to the server and insert the user data to the database. Before starting the tutorial, please take a look at the folders & files structure based on this example application. codeigniter-file-upload-tutorial-folders-files-structure-by-codexworld Creating Database Table (users): Before start to writing the code, create a table into your application’s database. For this example you can create a users table into the database with some basic fields. The users table SQL would like the below. CREATE TABLE `users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(100) COLLATE utf8_unicode_ci NOT NULL, `email` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `picture` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `created` datetime NOT NULL, `modified` datetime NOT NULL, `status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '1=Active, 0=Inactive', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; Controller (Users.php): Create a controller called Users.php. Place the following code in it and save this file to application/controllers/ directory. User model loaded into the __construct() function for inserting user data into the database. Initially, add() function will load the user adding form. When the form is submitted, picture would be uploaded and data would be inserted into the database via User model. load->model('user'); } function add(){ if($this->input->post('userSubmit')){ //Check whether user upload picture if(!empty($_FILES['picture']['name'])){ $config['upload_path'] = 'uploads/images/'; $config['allowed_types'] = 'jpg|jpeg|png|gif'; $config['file_name'] = $_FILES['picture']['name']; //Load upload library and initialize configuration $this->load->library('upload',$config); $this->upload->initialize($config); if($this->upload->do_upload('picture')){ $uploadData = $this->upload->data(); $picture = $uploadData['file_name']; }else{ $picture = ''; } }else{ $picture = ''; } //Prepare array of user data $userData = array( 'name' => $this->input->post('name'), 'email' => $this->input->post('email'), 'picture' => $picture ); //Pass user data to model $insertUserData = $this->user->insert($userData); //Storing insertion status message. if($insertUserData){ $this->session->set_flashdata('success_msg', 'User data have been added successfully.'); }else{ $this->session->set_flashdata('error_msg', 'Some problems occured, please try again.'); } } //Form for adding user data $this->load->view('users/add'); } } We’ve used some required Preferences in our file upload configuration. You can get all the available Preferences from here – https://codeigniter.com/user_guide/libraries/file_uploading.html#preferences Model (User.php): Create a model called User.php. Place the following code in it and save this file to application/models/ directory. insert() function insert the provided data into the users table. tableName = 'users'; $this->primaryKey = 'id'; } public function insert($data = array()){ if(!array_key_exists("created",$data)){ $data['created'] = date("Y-m-d H:i:s"); } if(!array_key_exists("modified",$data)){ $data['modified'] = date("Y-m-d H:i:s"); } $insert = $this->db->insert($this->tableName,$data); if($insert){ return $this->db->insert_id(); }else{ return false; } } } View (add.php): Create a view called add.php. Place the following code in it and save this file to application/views/users/ directory. add.php file contains form HTML, it is used to collect the user data and submit to the controller. session->flashdata('success_msg'); ?> session->flashdata('error_msg'); ?>
Creating Upload Directory: Create the uploads/images/ directory to storing the uploaded images. Conclusion In this tutorial, we’ve trying to show the basic example of CodeIgniter file upload. We hope you have learned how to upload a file in CodeIgniter using upload library. If you have any questions about CodeIgniter file upload, let us know by commenting here. Previous Smooth scroll to div using jQuery Next Autocomplete Textbox with Multiple Values using jQuery, PHP and MySQL RECOMMENDED TUTORIALS FOR YOU 11 Comments MUHAMMAD SHAFIQ BIN MOHD YA'ACUB Said... I can insert the data into table but the file is not uploaded…does it need to declare in autoload? January 13, 2017 at 2:46 AM CodexWorld Said... No, the upload library is loaded into the add() method of Users controller. So, you don’t need to load it into the autoload. In your case, you can check whether the uploads/images/ directory has writable permission. January 15, 2017 at 4:33 PM Salih Said... Thank you, and waiting for that. January 3, 2017 at 4:52 AM Salih Said... Can you show an example with form validation, I mean for this script If I add validation rule, If name and email field is not valid and File field valid then file should not upload… How to do that, without js/ajax. I have asked the same question at StackOverlfow, here is the link for more about my question:::: http://stackoverflow.com/questions/41414281/is-there-a-better-way-of-multipart-form-data-validation January 2, 2017 at 10:10 AM CodexWorld Said... @Salih We’ll try to publish your requested tutorial soon. Please subscribe our newsletter to get notified. January 2, 2017 at 7:04 PM Allen Said... thank you , your tutorial let me learn more November 23, 2016 at 3:17 AM Mounika Said... thank u i used this code…it works great… November 18, 2016 at 10:33 AM Navyaksh Said... great code September 22, 2016 at 11:41 AM Gus Bala Said... Thanks helpful tutorial, could you make some vote system tutorial ? Big thanks from me. September 8, 2016 at 2:34 AM CodexWorld Said... @Gus We’ll try to publish your requested tutorial soon. Meanwhile, subscribe our newsletter to get the notification about new tutorial. September 8, 2016 at 6:49 PM Vinod Sahare Said... very good tutorial it is very helpful for me August 4, 2016 at 3:59 PM Leave a reply Comment* Your Name* Your Email* Your Website Post Comment CONNECT WITH CODEXWORLD Subscribe CodexWorld updates via email and get every new post delivered to your inbox. Enter email address SUBSCRIBEFacebookTwitterGoogle+LinkedINPinterestYouTubeRSS Feed TRENDING TUTORIALS Login with Facebook using PHP Drag and Drop Reorder Images using jQuery, Ajax, PHP & MySQL Login with Google Account using PHP PayPal Standard Payment Gateway Integration in PHP Add Remove input fields dynamically using jQuery Upload multiple images using jQuery, Ajax and PHP CodeIgniter Tutorial for Beginners Login with Twitter using PHP TOPICS CakePHPCodeIgniterDrupalFacebookGoogleAPIGoogleMaphtaccessHTML&CSSHTML5JavaScriptMySQLPayPalPHPSocial MediaTwitterUbuntuWeb DevelopmentWordPress LATEST HOW TO GUIDES How to Monitor Ajax Requests in Chrome How to Make Phone Number Clickable on Mobile Devices How to Disable Click Event using jQuery How to Filter Array by Value in PHP How to Calculate Age from Date of Birth in PHP Copyright © 2017 CodexWorld. All rights reserved. Creative Commons License About Us|Privacy Policy|Terms & Conditions|Write For Us|Contact Top