File Upload in CodeIgniter 4 Example Tutorial

Last Updated on by in CodeIgniter
File uploading is a considerable imperative that allows your site visitors to upload various files. Such as images, word documents, excel and pdf reports, etc. on a web server.In this tutorial, we will learn how to upload files in Codeigniter 4 from scratch.File uploading is a task that is ideally done by many of us daily. As users, we end up uploading multiple files relentlessly on Facebook, WhatsApp, Instagram, etc.

CodeIgniter comes with a default File Uploading class, which makes your image and other documents easily upload on the server. To impetus the file uploading task, we will shed light on Codeigniter’s file upload library.

CodeIgniter Image Uploading Example

The assortment of this tutorial is in two primary parts backend and frontend. In the backend part, we take care of imperatives, such as creating a database connection, model, and routes etc.

The Frontend part consists of using HTML Form input element to create a file uploading component. We will take the help of the Bootstrap framework to accomplish this task.

It refrains us from wasting a ton of time that we are going to invest in designing a layout for the image uploading component.

Set Up Codeigniter Application

Hit the below command to install the CodeIgniter 4 application, but you must have a composer package installed on your device.

composer create-project codeigniter4/appstarter

Rename the Codeigniter app name, such as codeigniter-file-upload.

Go inside the project folder.

cd codeigniter-file-upload

Enable Errors in CI

Enable error reporting to debug the error with gravitas in the Codeigniter application.

Open app/Config/Boot/development.php file and set the display_errors to 1 instead of 0. Do the same thing in app/Config/Boot/production.php file.

ini_set('display_errors', '1');

Formulate Database with Table

Go to PHPMyAdmin, execute the following SQL query to manifest a database with demo name, also create a users table within. Here we store the uploaded files or images.

    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',
    PRIMARY KEY (id)

Database Connection

To establish the coherence between database and codeigniter you must define database name, username and password in app/config/database.php.

public $default = [
        'DSN'      => '',
        'hostname' => 'localhost',
        'username' => 'root',
        'password' => 'root',
        '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,


There are a high chance that you might get Unable to connect database : Codeigniter the error, especially if you are working with MAMP or XAMP servers. You can define either of the hostname for MAMP or XAMP.

public $default = [
  'hostname' => '/Applications/XAMPP/xamppfiles/var/mysql/mysql.sock',

public $default = [
  'hostname' => '/Applications/MAMP/tmp/mysql/mysql.sock',

Create Image Upload Controller

Create a FileUpload.php controller in app/Controllers directory. Then, place the below-mentioned code in it.

namespace App\Controllers;
// use App\Models\FormModel;
use CodeIgniter\Controller;

class FileUpload extends Controller

    public function index() 
        return view('home');

    function upload() { 
        helper(['form', 'url']);
        $database = \Config\Database::connect();
        $db = $database->table('users');
        $input = $this->validate([
            'file' => [
        if (!$input) {
            print_r('Choose a valid file');
        } else {
            $img = $this->request->getFile('file');
            $img->move(WRITEPATH . 'uploads');
            $data = [
               'name' =>  $img->getName(),
               'type'  => $img->getClientMimeType()
            $save = $db->insert($data);
            print_r('File has successfully uploaded');        


Create Routes

We have to create a route that loads the file uploading controller when the application starts. Open app/Config/Routes.php file and add the following code.

 * --------------------------------------------------------------------
 * Route Definitions
 * --------------------------------------------------------------------

$routes->get('/', 'FileUpload::index');
$routes->match(['get', 'post'], 'FileUpload/upload', 'FileUpload::upload');

Create Image Upload View

Eventually, we require to create a file uploading HTML component using Bootstrap. So, create app/Views/home.php file and place the given below code in it.

<!doctype html>
<html lang="en">

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <title>Codeigniter 4 File Upload -</title>
  <link rel="stylesheet" href="">
    .container {
      max-width: 500px;

  <div class="container mt-5">

    <form method="post" action="<?php echo base_url('FileUpload/upload');?>" enctype="multipart/form-data">
      <div class="form-group">
        <input type="file" name="file" class="form-control">

      <div class="form-group">
        <button type="submit" class="btn btn-danger">Upload</button>



Start Application

Let us start the app, run the following command to start the application:

php spark serve

Enter the following URL in the browser to upload the image into the database in Codeigniter:


Download the complete code of this tutorial from GitHub.

Digamber - Author

Hi, I'm Digamber Singh, a New Delhi-based full-stack developer, tech author, and open-source contributor with 10+ years' experience in HTML, CSS, JavaScript, PHP, and WordPress.