6 Steps to Create a File Upload System Script in CodeIgniter

File Upload System Script in CodeIgniter, In this tutorial you are going to learn about creating file upload system in CodeIgniter. Previously, I’ve created a crud application in CodeIgniter, You can go through the tutorial. In this file upload system, I’m going to upload a file using CodeIgniter and inserting it into the database. Displaying all the uploaded files and deleting uploaded files. These are the functions we are going to build in this tutorial.
=> Creating File Upload System Script in PHP & MySQL
=> Create CRUD Application in CodeIgniter
1. Download CodeIgniter & Setup
First of all download Code Igniter from codeigniter.com website, I’m using Code Igniter 3.1.5 for this CRUD application. This is the latest version available. Extract this package, place these files on your server. Update htaccess file with this below code to remove index.php from URL, By default the index.php file, will be included in your URLs
1 2 3 4 |
RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php/$1 [L] |
Open config.php file from application->config->config.php and update base URL with the path where you have uploaded. In my case I’ve uploaded to http://localhost/ciupload/, in your case it may be different.
1 |
$config['base_url'] = 'http://localhost/ciupload/'; |
Remove index.php from below line of code and make it blank.
From this code
1 |
$config['index_page'] = 'index.php'; |
1 |
$config['index_page'] = ''; |
2. Create Database & Table
We are going to work on application directory. In this directory, we will create all the necessary files for models views and controllers. Next, we need to configure the database in CodeIgniter.
Before that create database and database table, below is the SQL code of database table.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
-- -- Table structure for table `upload` -- CREATE TABLE `upload` ( `id` int(11) NOT NULL, `name` varchar(256) NOT NULL, `size` int(11) NOT NULL, `type` varchar(256) NOT NULL, `location` varchar(256) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Indexes for table `upload` -- ALTER TABLE `upload` ADD PRIMARY KEY (`id`); -- -- AUTO_INCREMENT for table `upload` -- ALTER TABLE `upload` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;COMMIT; |
3. Authenticate in CodeIgniter
In database.php file update the database user name, password & database name. You can find database.php file in application-> config-> database.php
1 2 3 4 5 |
'hostname' => 'localhost', 'username' => 'root', 'password' => '', 'database' => 'ciupload', 'dbdriver' => 'mysqli', |
4. Creating File Upload Form View
Then I’m going to create a view for our File Upload form. Before that I’ll create a directory under views with the name of fileupload. Inside this fileupload directory, I’m going to create new php file and save it as upload.php.
In this upload.php file, I’m going to add basic html with bootstrap cdn files and the form.
1 2 3 4 5 6 7 8 9 10 |
<!DOCTYPE html> <html> <head> <title>File Upload System Script - CodeIgniter</title> </head> <body> </body> </html> |
Adding bootstrap CDN files
1 2 3 4 5 6 7 8 9 |
<!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" > <!-- Optional theme --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" > <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <!-- Latest compiled and minified JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> |
Adding form inside upload.php file within body section
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<div class="container"> <div class="row"> <?php echo form_open_multipart(site_url('upload/do_upload'));?> <h2 class="form-signin-heading">Upload File</h2> <div class="form-group"> <label for="InputFile">File input</label> <input type="file" name="ufile" id="InputFile"> <p class="help-block">Upload JPEG Files that are below 100 KiloBytes</p> </div> <button class="btn btn-lg btn-primary btn-block" type="submit">Upload</button> </form> </div> </div> |
5. Creating Controller with Index Method & Constructor
After creating the view, I’m going to create a controller to display the form and send submitted values to model. I’ll create both controller methods. One with the name of index and the another one with the name of do_upload.
Before creating index method. I’ll create a constructor to load form helper and url helper, also to load model I’ll name it as upload_model which will be used in next steps. Create a file under controllers directory and save it as upload.php. Then add this below code.
1 2 3 4 5 6 7 8 9 10 11 |
defined('BASEPATH') OR exit('No direct script access allowed'); class Upload extends CI_Controller { public function __construct() { parent::__construct(); $this->load->helper(array('form', 'url')); $this->load->model('upload_model'); } } |
Then I’m creating Index method in our controller file.
1 2 3 4 |
public function index() { $this->load->view('fileupload/upload',array('error' => ' ' )); } |
If you open the url in browser you can see the form your-file-path/upload/index
6. File Upload Method in Controller
Next, I’m going to create a controller method with the name of do_upload. First I’ll define the configuration variables, then I’m going to load file upload library with the configuration options defined. After that, I’m going to write an if condition to check file upload. If there are any errors we will display the errors and then sends these errors to upload index view.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<?php public function do_upload(){ $config['upload_path'] = './uploads/'; $config['allowed_types'] = 'gif|jpg|png'; $config['max_size'] = 100000; $this->load->library('upload', $config); if ( ! $this->upload->do_upload('ufile')) { $error = array('error' => $this->upload->display_errors()); $this->load->view('fileupload/upload', $error); } else { //upload files to server and insert into database } } |
If there are no errors I’ll upload the file to the server and insert the record into our upload database table.
1 2 3 4 5 6 |
$datav = $this->upload->data(); //insert query here using model $data = array('upload_data' => $datav); $this->load->view('fileupload/uploadsuccess', $data); |
7. Creating Model to Insert Data & Constructor
Next we need a model to insert submitted data into database. For that I’m going to create a model with constructor that loads database.
1 2 3 4 5 6 7 8 9 |
<?php class Upload_model extends CI_Model{ public function __construct(){ parent::__construct(); $this->load->database(); } } |
Next is an insert query to insert the data into database.
1 2 3 |
public function insert_upload($file_name,$size,$type,$location){ $this->db->query("insert into upload(name,size,type,location) values('$file_name','$size','$type','$location')"); } |
Add this line of code in the else block of do_upload controller method
1 |
$this->upload_model->insert_upload($datav['file_name'],$datav['file_type'],$datav['file_size'],$datav['file_path']); |
8. Creating View for Displaying Errors
Add this below code in upload.php file under views. This line should be above form opening tag.
1 |
<?php echo $error; ?> |
9. Creating View to Display all the uploaded files
I’m creating a view for displaying uploaded files with a table.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
<!DOCTYPE html> <html> <head> <title>File Upload System Script in CodeIgniter</title> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" > <!-- Optional theme --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" > <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <!-- Latest compiled and minified JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <div class="row"> <table class="table"> <thead> <tr> <th>S.No</th> <th>Name</th> <th>Size</th> <th>Type</th> <th>Location</th> <th>Delete</th> </tr> </thead> <tbody> <tr> <th scope="row">S.No</th> <td>Name</td> <td>Size</td> <td>Type</td> <td>Location</td> <td><a href="#">Delete</a></td> </tr> </tbody> </table> </div> </div> </body> </html> |
10. Add View Method in Controller
Creating View Method in Controller to display our view to list all the records.
1 2 3 |
public function view(){ $this->load->view('fileupload/view'); } |
11. Fetching records from Database using Model
Selecting all the records from uploads table using get_uploads method from upload model.
1 2 3 4 |
public function get_uploads(){ $query = $this->db->query("select * from upload"); return $query; } |
12. Displaying Records the View
Displaying Records from database using model method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<?php $query = $this->upload_model->get_uploads(); foreach($query->result() as $row){ ?> <tr> <th scope="row"><?php echo $row->id; ?></th> <td><?php echo $row->name; ?></td> <td><?php echo $row->size; ?></td> <td><?php echo $row->type; ?></td> <td><?php echo $row->location; ?></td> <td><a href="<?php echo site_url('upload/delete/'.$row->id); ?>">Delete</a></td> </tr> <?php } ?> |
13. Creating Delete Method in Controller
Final step is creating Delete method in Controller
1 2 3 4 5 |
public function delete($number){ $delete_upload = $this->upload_model->delete_upload($number); unlink($delete_upload->location.'/'.$delete_upload->name); redirect('upload/view'); } |
14. Add Delete Model to Delete Uploaded File
I’m creating a delete_upload method to delete record from database and also to delte file from controller.
1 2 3 4 5 6 7 8 |
public function delete_upload($num){ $query = $this->db->query("select * from upload where id='$num'"); if($query->num_rows() == 1 ){ $info = $query->row(); $this->db->query("delete from upload where id='$num'"); return $info; } } |
If you are getting any problem let me know through comment form below.