Codeigniter 4 File Upload Validation Example

CodeIgniter 4 file upload validation example. In this example tutorial, i will guide you step by step on how to upload file with validation in Codeigniter 4 apps using codeigniter 4 build in library.

If you are creating any form with file upload field in codeigniter 4 app. And want to upload file like pdf, excel, csv with validation in codeigniter 4 apps. So, in this tutorial, you will learn how to upload file with validation in codeigniter 4 apps.

In CodeIgniter 4, there is CodeIgniter\Validation\FileRules that can be used out of the box from validate() from controllers that you can using it on upload process.

Like you are building any social media, e-commerce web application in codeigniter 4 apps. At that time, Uploading files is a basic requirement in this types of applications. File uploading is an important requirement that allows your site visitors to upload various files.

For the CodeIgniter 4 file upload with validation example , I’ll create a simple form and upload file like csv, excel, pdf and text with validation in codeigniter 4 apps. And store file into database and codeigniter 4 apps directory.

How to Upload File With Validation In Codeigniter 4 Apps

You can learn by following the steps given below on codeIgniter 4 file upload validation example:

  • Install Codeigniter 4 Application
  • Basic App Configurations
  • Create Database and Table
  • Setup Database Credentials
  • Create Controller
  • Create Views
  • Setup Routes
  • Start Development server

Step 1 – Install Codeigniter 4 Application

Now, you need to ownload the latest version of Codeigniter 4. So, visit this link Download Codeigniter 4 app and unzip the setup in your local system xampp/htdocs/ .

Note that, please change the download folder name “demo”.

Step 2 – Basic App Configurations

Now, you need to some basic configuration on the app/config/app.php file, so let’s go to application/config/config.php and open this file on text editor.

Set Base URL like this

public $baseURL = 'http://localhost:8080';
public $baseURL = 'http://localhost/demo/';

Step 3 – Create Database and Table

Create a database table by executing the following SQL query:


    id int(11) NOT NULL AUTO_INCREMENT COMMENT 'Primary Key',
    name varchar(100) NOT NULL COMMENT 'Name',
    type varchar(255) NOT NULL COMMENT 'file type',
    created_at varchar(20) NOT NULL COMMENT 'Created date',
    PRIMARY KEY (id)

Step 4 – Setup Database Credentials

To connect your codeigniter 4 app to the database. So, visit app/Config/ directory and open Database.php. Then add the databasae details like below into database.php file:

public $default = [
        'DSN'      => '',
        'hostname' => 'localhost',
        'username' => 'test',
        'password' => '4Mu99BhzK8dr4vF1',
        'database' => 'demo',
        'DBDriver' => 'MySQLi',
        'DBPrefix' => '',
        'pConnect' => false,
        'DBDebug'  => (ENVIRONMENT !== 'development'),
        'cacheOn'  => false,
        'cacheDir' => '',
        'charset'  => 'utf8',
        'DBCollat' => 'utf8_general_ci',
        'swapPre'  => '',
        'encrypt'  => false,
        'compress' => false,
        'strictOn' => false,
        'failover' => [],
        'port'     => 3306,

Step 5 – Create Controller

Create FormController.php file. So, visit app/Controllers directory and create FileUploadController.php.Then add the following code into it:

<?php namespace App\Controllers;

use CodeIgniter\Controller;

class FileUploadController extends Controller
    public function index()
         return view('file_upload_form');

   public function store()

	 helper(['form', 'url']);
	 $db      = \Config\Database::connect();
         $builder = $db->table('files');

        $validated = $this->validate([
            'file' => [

        $msg = 'Please select a valid file';
        if ($validated) {
            $avatar = $this->request->getFile('file');
            $avatar->move(WRITEPATH . 'uploads');

          $data = [

            'name' =>  $avatar->getClientName(),
            'type'  => $avatar->getClientMimeType()

          $save = $builder->insert($data);
          $msg = 'Filehas been uploaded';

       return redirect()->to( base_url('/') )->with('msg', $msg);


The index() function renders the contact form template into the view.

The store() method handles the form of validation and contains various variables. And store file into db and directory.

Step 6 – Create Views

Create file_upload_form.php view file, so visit application/views/ directory and create file_upload_form.php file. Then add the following HTML into file_upload_form.php file:

<!DOCTYPE html>
  <title>Codeigniter 4 File upload example -</title>
 <link rel="stylesheet" href="">

 <div class="container">
    <?php if (session('msg')) : ?>
        <div class="alert alert-info alert-dismissible">
            <?= session('msg') ?>
            <button type="button" class="close" data-dismiss="alert"><span>×</span></button>
    <?php endif ?>

    <div class="row">
      <div class="col-md-9">
        <form action="<?php echo base_url('FileUploadController/store');?>" name="file_upload_form" id="file_upload_form" method="post" accept-charset="utf-8" enctype="multipart/form-data">

          <div class="form-group">
            <label for="formGroupExampleInput">Name</label>
            <input type="file" name="file" class="form-control" id="file">

          <div class="form-group">
           <button type="submit" id="send_form" class="btn btn-success">Submit</button>


Step 7 – Setup Routes

To define a route, So, visit app/Config/ directory and open Routes.php file. Then add the following routes into it:

$routes->get('/', 'FileUploadController::index');

Note that, the routes will be displaying the file upload form and submitting the data in the database on successful form submission.

Step 8 – Start Development server

Execute the following command into command prompt or terminal to start the codeigniter 4 application:

php spark serve

Then visit your web browser and hit the following url on it:





CodeIgniter 4 file upload validation example tutorial. In this example,you have learned how to upload file with validation in Codeigniter 4 apps. And also will learned how to store file into db and directory..

Recommende CodeIgniter 4 Tutorial

  1. How to Install / Download Codeigniter 4 By Manual, Composer, Git
  2. How to Remove Public and Index.php From URL in Codeigniter 4
  3. Codeigniter 4 Form Validation Example Tutorial
  4. How to add jQuery Validation on Form in Codeigniter 4 Example
  5. Codeigniter 4 Ajax Form Submit Validation Example
  6. Codeigniter 4 Image Upload Example

Leave a Comment