File Upload in Codeigniter 4 Example Tutorial

Last updated on by Digamber
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.

CREATE TABLE users (
    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)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='users table' AUTO_INCREMENT=1;

Database Connection

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

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,
	];

Create Image Upload Controller

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

<?php 
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' => [
                'uploaded[file]',
                'mime_in[file,image/jpg,image/jpeg,image/png]',
                'max_size[file,1024]',
            ]
        ]);
    
        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.

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

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">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <title>Codeigniter 4 File Upload - positronx.io</title>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
  <style>
    .container {
      max-width: 500px;
    }
  </style>
</head>

<body>
  <div class="container mt-5">

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

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

  </div>
</body>

</html>

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:

http://localhost:8080

Download the complete code of this tutorial from GitHub.