Code your dreams into reality.
Every line of code is a step towards a better future.
Embrace the bugs, they make you a better debugger.

CodeIgniter 4 File Upload Validation Tutorial

Last Updated on July 17, 2024 by

CodeIgniter 4 has many built-in functions that help developers create file upload functionality and validate file type, size, etc.

Let’s start to creating a file upload feature with validation in application:

Step 1 – Set up CodeIgniter 4

To download CodeIgniter 4 from the official website, Link: https://codeigniter.com/user_guide/installation/index.html.

Extract downloaded zip file in xampp/htdocs directory. and edit app/Config/App.php file, and set up base url in it:

public $baseURL = 'http://localhost/your-project/public';

Step 2 – Create File Upload Form

Create a view file named file_form.php in app/Views directory:

<!-- app/Views/file_upload.php -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Codeigniter File Upload Validation - Itcodstuff.com</title>
</head>
<body>
    <h1>File Upload</h1>

    <?php if (session()->getFlashdata('success')): ?>
        <p><?= session()->getFlashdata('success') ?></p>
    <?php endif; ?>

    <?php if (session()->getFlashdata('error')): ?>
        <p><?= session()->getFlashdata('error') ?></p>
    <?php endif; ?>

    <?php if (session()->getFlashdata('errors')): ?>
        <ul>
            <?php foreach (session()->getFlashdata('errors') as $error): ?>
                <li><?= $error ?></li>
            <?php endforeach; ?>
        </ul>
    <?php endif; ?>

    <form action="<?= site_url('file-upload/upload') ?>" method="post" enctype="multipart/form-data">
        <?= csrf_field() ?>
        <input type="file" name="file">
        <button type="submit">Upload</button>
    </form>
</body>
</html>

Step 3 – Create Upload Directory

Run the following command to create upload and set permissions:

mkdir writable/uploads
chmod -R 777 writable/uploads

Step 4 – Create Controller Class

Go to app/controllers directory, and create a controller file named FileUploadController.php, and create methods in it to handle file upload with validation:

<?php

namespace App\Controllers;

use CodeIgniter\Controller;

class FileUploadController extends Controller
{
    public function index()
    {
        return view('file_upload');
    }

    public function upload()
    {
        $validationRule = [
            'file' => [
                'label' => 'File',
                'rules' => 'uploaded[file]'
                    . '|mime_in[file,image/jpg,image/jpeg,image/png]'
                    . '|max_size[file,2048]'
            ],
        ];

        if (!$this->validate($validationRule)) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

        $file = $this->request->getFile('file');
        if ($file->isValid() && !$file->hasMoved()) {
            $file->move(WRITEPATH . 'uploads');
            return redirect()->back()->with('success', 'File has been uploaded');
        }

        return redirect()->back()->with('error', 'File upload failed');
    }
}

Step 5 – Define Routes

Edit app/Config/Routes.php and define the routes to handle file upload requests:

// app/Config/Routes.php
$routes->get('file-upload', 'FileUploadController::index');
$routes->post('file-upload/upload', 'FileUploadController::upload');

Step 6 – Test Application

Run the following command to start application server:

cd /your-project
php spark serve

Open your browser and type to http://localhost:8080/file-upload url in it to test this application.

Leave a Comment