CodeIgniter Part 4: File Handling - Uploading files into a folder and database

in #utopian-io7 years ago

mrobele-ci-file-handling.jpg

Repository

CodeIgniter Github Repository

What will I learn?

In this tutorial you will learn the following:

  • How to create a file upload field on a form using codeigniter form helper method
  • How to properly configure the file components such as the upload path, required file size, required file dimensions
  • How to validate the file and display notification message using the codeigniter file methods
  • How to save the file to the database

Requirements

  • A good knowledge of PHP OOP programming
  • Understanding of HTML, CSS
  • Understanding of MVC flow pattern in CodeIgniter
  • Knowledge of database administration tools (I will be using phpMyAdmin in this tutorial for MySQL database administration).
  • A working server, local or live server to run the application
  • A good text editor of your choice for proper writing and formatting of your code (I’m using visual studio code in this tutorial)
  • Previous tutorial

Difficulty

Intermediate

Tutorial Contents

  • Create the view to hold the file upload field.
  • Configure the file upload rules.
  • Validate the file to be uploaded and show notification messages.
  • Save the file to the database.

Create the view to hold the file upload field:

Let’s create the view to enable the user upload the file, if you’ve been following this tutorial series up to this point then your view folder structure should be like this
mrobele-ci-file-handling-view-structure.jpg

If you are just joining, just create the folders and files as in the views structure above. For the scope of this tutorial, I will be including only the code for the file_upload.php view but I will include a link ere you can access the full project for your practice.
We will be working with just three views, these are;

  • Views/layouts/main.php: this is the main layout were other views will be displayed.
  • Views/home.php: this will be used to display the success message to the user on successful file upload.
  • Views/Users/file_upload.php: this is the view in focus, it will provide the interface for the user to select the desired file for upload.
    Here is the form
    mrobele-file-upload-view.jpg

Below is the code for this;

  <div class="well" style="width:301px;text-align: center">
<h1>File Upload</h1>
<p style="font-size:19px;">Kindly select a file to upload</p>
(html comment removed: Display Errors)

<?php if($this->session->flashdata('upload_failed')) : ?>
  <p class="alert alert-dismissable alert-success text-center"><?php echo $this->session->flashdata('upload_failed');?></p>
<?php endif; ?>

<?php if($this->session->flashdata('image_error')) : ?>
  <p class="alert alert-dismissable alert-danger text-center"><?php echo $this->session->flashdata('image_error');?></p>
<?php endif; ?>

<?php $attributes = array('id' => 'login_form','class'=> 'form-horizontal','enctype'=>'multipart/form-data','role'=>'form');?>
<?php echo form_open('Upload/uploadFile',$attributes); ?>

(html comment removed: field: Document )
<p>
    <?php echo form_label('Document: '); ?>
  <br /><em style="color:red;">*Allowed file types doc, docx, pdf, jpg, jpeg, png (max size: 1mb)*</em>
    <?php
    $data = array(
        'name'  => 'document',
        'type' => 'file',
        'class' => 'form_control'
        );

        ?>
        <?php echo form_input($data); ?>
</p>
(html comment removed: field: Submit Buttons)
<p>
  <?php
  $data = array(
    'name'  => 'submit',
    'value' => 'Upload',
    'class' => 'btn'
    );

    ?>
    <?php echo form_submit($data); ?>
</p>

<?php echo form_close(); ?>
</div>

From the above code, I have used the below set of codes to display the notification messages to the user and also initialized the form attributes and action

<?php if($this->session->flashdata('upload_failed')) : ?>
  <p class="alert alert-dismissable alert-success text-center"><?php echo $this->session->flashdata('upload_failed');?></p>
<?php endif; ?>

<?php if($this->session->flashdata('image_error')) : ?>
  <p class="alert alert-dismissable alert-danger text-center"><?php echo $this->session->flashdata('image_error');?></p>
<?php endif; ?>

<?php $attributes = array('id' => 'login_form','class'=> 'form-horizontal','enctype'=>'multipart/form-data','role'=>'form');?>
<?php echo form_open('Upload/uploadFile',$attributes); ?>

I earlier explained this in the Previous Tutorial
And here is the file upload field we just added.

(html comment removed: field: Document )
<p>
    <?php echo form_label('Document: '); ?>
  <br /><em style="color:red;">*Allowed file types doc, docx, pdf, jpg, jpeg, png (max size: 1mb)*</em>
    <?php
    $data = array(
        'name'  => 'document',
        'type' => 'file',
        'class' => 'form_control'
        );

        ?>
        <?php echo form_input($data); ?>
</p>

Also here is the css for the design for the form design.

 body{
    background:url(../images/background2.jpg);
    background-size: cover;
    background-repeat: no-repeat;
    color: white;
}
h1, h2, h3{
    color: rgba(255, 87, 34, 0.87);
}
hr{
    border:1px !important;
}

.middle-form{
    width: 400px;
    margin: 0 auto;
}
.home-div{
    margin-top: 50px;
}
.well{
    margin: 0 auto;
    background-color: rgba(13, 12, 12, 0.33)! important;
    color: white;
    margin-bottom: 50px;
    border: none;
}

.col-md-12{
    background-size: cover;
    background-repeat: no-repeat;
}

.btn{
    background-color: #DD5347;
    border-radius: 0;
    padding: 10px;
    border-color: #DD5347;
}

form{
    color: white;
    text-align: left;
    width: auto;
    margin: auto;
    margin-bottom: 50px;
}
input, select,option{
    background-color: rgba(255, 254, 254, 0.29);
    border: none;
}

.logoImage{
    width: 30px;
    height: 30px;
}

.theader{
    color: white;
    font-size: 20px;
}

.trow{
    background-color: black;
}

.home-text{
    color: #ffffff;
}

#upload-link{
    float: right;
    /* margin-right: 139px; */
    position: absolute;
    left: 41%;
}

Configure the file upload rules

For this and the other two sections we will be working with the Upload* controller and Upload_model.
From your Controllers folder, create a file called Upload.php and add the following code;

 <?php

if (!defined('BASEPATH')) {
    exit('No direct script access allowed');
}

class Upload extends CI_Controller{
    public function __Construct() {
        parent::__Construct();
       } 

    public function index(){
        $data['main_content'] = 'Users/file_upload';
        $this->load->view('layouts/main',$data);
        
    }
    
public function uploadFile(){
        
 //file upload configuration
  $config['upload_path']          = './assets/documents/';// directory path to save the file
  $config['allowed_types']        = 'doc|docx|pdfpdf|gif|jpg|png';// allowed file types
  $config['max_size']             = 80;// maximum file size allowed in kilobytes
  $config['max_width']            = 200;// maximum width in pixels
  $config['max_height']           = 100;// maximum height in pixels
  $this->load->library('upload', $config); // Load the upload library

        if(!$this->upload->do_upload('document')){ // check if the file upload is not successful

            //set file upload error message
            $this->session->set_flashdata('image_error',$this->upload->display_errors()); //set the error message

            //re-load signup page to display error

            $data['main_content'] = 'Users/file_upload';
            $this->load->view('layouts/main',$data);

        } else {
             
             //document details
            $filedata =  $this->upload->data();
            $filename = $filedata['file_name'];
            //save the file to the database 
             $data = array(
            'file'    =>$filename
            );

            if ($this->Upload_model->upload_document($data)) {

                $this->session->set_flashdata('upload_success','Document uploaded successfully');
                redirect(base_url('Home'));
            }
            else{
                $this->session->set_flashdata('upload_failed','unable to save your details try again');
                redirect(base_url('Upload'));

            }   

        }
    }

}
?>

I’ve added comments in the code for a clearer understanding but let’ take a look at the configuration part, in the ***upload file method, let me explain the config code below.

$config['upload_path']         = './assets/documents/';// directory path to save the file
$config['allowed_types']      = 'doc|docx|pdfpdf|gif|jpg|png';// allowed file types
$config['max_size']               = 80;// maximum file size allowed in kilobytes
$config['max_width']            = 200;// maximum width in pixels
$config['max_height']           = 100;// maximum height in pixels
$this->load->library('upload', $config); // Load the upload library

From the above code, the first line is used to specify the folder where the files uploaded should be saved, you can specify any path, just ensure that you are specifying the right directory structure. I’ve used the path, ./assets/documents because I created a folder called documents inside of assets directory, and the ./ is because the we are inside the controller so to access the assets directory we need to moved out a step. With this properly set, once a file is uploaded it will be saved in this directory.
The second line is used to specify the accepted file types, all you need to do is add the file extension types required for upload.
The third line specifies the maximum file size allowed in kilobytes.
The fourth and fifth line specifies the maximum width and maximum heights allowed, these fields will serve as the validation points for us in the next section.

Once this is set up you can then load the upload library as below:

 $this->load->library('upload', $config);

I have loaded this library here in the controller since we have been auto loading our libraries previously, this is to give you an Idea of how to load libraries in the controller this also applies to loading helpers and models too.

Validate the file to be uploaded and show notification messages.

We’ve already done the file configuration from the above section, here we will check if these configurations have been met by the user so CodeIgniter can automatically display the message for each violation. Let’s look at the code below still in the fileUpload method of the Upload Controller;

    if(!$this->upload->do_upload('document')){ // check if the file upload is not successful

    /set file upload error message
    $this->session->set_flashdata('image_error',$this->upload->display_errors()); //set the error message

    //re-load signup page to display error

    $data['main_content'] = 'Users/file_upload';
    $this->load->view('layouts/main',$data);

        }

The above code uses the method upload->do_upload() to check if the file was uploaded or not due to violation of the set of rules configured, if there is any then we set a session of the error message as stated by codeigniter using the method upload->display_errors() this method contains the predefined error for each violation, let’s say if the user enters a file larger than the configured size, it will display an error related to the file size. Here I’ve called the error message variable as image_error we can then redirect the user back to the file_upload view and display this error as below:

<?php if($this->session->flashdata('image_error')) : ?>
  <p class="alert alert-dismissable alert-danger text-center"><?php echo $this->session->flashdata('image_error');?></p>
<?php endif; ?>

You should be very familiar with this as we’ve covered it extensively in the Previous tutorial.

Save the file to the database

We can now prepare the environment to save the file to the database, head up to your database management tool and create a new database called ** ci-file-handling**, I’m using phpMyadmin, once you have created the database if on phpMyadmin click on the database name and from the right click on SQL and run the following script to create the files table

CREATE TABLE `files` (
 `id` int(11) PRIMARY KEY NOT NULL AUTO_INCREMENT,
`file` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

mrobele-ci-file-handling-database.jpg

Once you have done this, go to you databse.php file of the development folder in the config directory and add the new database as shown below.
mrobele-ci-file-handling-database-name.jpg

With these set up we can now save the file to the database, let’s look at the code in the fileUpload method of the Upload controller for this.

        /document details
$filedata =  $this->upload->data();//get the uploaded file data
$filename = $filedata['file_name'];//get the file name into a variable as $filedata variable 
contains other values such as size type and other 
//save the file to the database 
$data = array(
'file'    =>$filename //set the file name to the corresponding table column name in our case file 
is the column name
);
if ($this->Upload_model->upload_document($data)) { 
//check if the file was save to the databse from the upload_document method of the Upload_model
//if successful set a success message and redirect to the home page to display the message
$this->session->set_flashdata('upload_success','Document uploaded successfully');
redirect(base_url('Home'));
}
else{
// if saving the data failed then set the upload_failed message and reload the file_upload view to display the error message
$this->session->set_flashdata('upload_failed','unable to save your details try again');
redirect(base_url('Upload'));
}

from the above code, we save the uploaded file data into a variable and extract the file name, This file name is then sent to the Upload_model with the table column where to store the name specified, we then check if the operation from the model was successful or not, depending on the response from the model we then set appropriate message either error message or success message, if success message we redirect to the home view and display the message, and if an error message then we reload the file_upload view and display the error message
Here is the Upload_model code.

<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
 /**
 * 
 */
 class Upload_model extends CI_Model
 {
    public function upload_document($data)
    {
        $insert = $this->db->insert('files',$data););// save the data sent from the controller to the files table
        return $insert;
    
    }

 }

?>

The above code, takes the data sent from the controller and interacts with the database and then returns the response to the controller about the file data.

This brings us to the end of this part of the tutorial series feel free to view the full code as I will be providing the github link for your study purpose.

Curriculum

Proof of work done

GitHub repository for this tutorial
https://github.com/MrObele/CI-File-Handling

Sort:  

Get your post resteemed to 72,000 followers. Go here https://steemit.com/@a-a-a

Thank you for your contribution.
Your contribution will not be rewarded for the following reasons:

  • There is a lot of information on this subject for example: Link, try to find something more innovative and contribute to the open source community.

Need help? Write a ticket on https://support.utopian.io/.
Chat with us on Discord.
[utopian-moderator]

Thank you @portugalcion, I have written about this to the simplest form for the new commers due to the difficulties i faced my self on getting to this aspect of codeigniter. Following your observation, do you mean i should only write about that which has never existed at all? I will try to be more innovative in my subsequent contributions.

Coin Marketplace

STEEM 0.23
TRX 0.26
JST 0.040
BTC 98098.76
ETH 3483.62
USDT 1.00
SBD 3.27