Codeigniter 4 File/Image Upload and Validation Tutorial

Codeigniter 4 Image Upload tutorial; In this tutorial, we will teach how to create an image upload feature in the Codeigniter app and how to validate the image file before uploading it to the server.

This File upload in CodeIgniter 4 example is the ultimate elixir if:

=> You are new to Codeigniter development.

=> You want to learn swiftly about File upload in the Codeigniter 4 app.

=> You want to learn how to use the database to store files.

=> You want to amplify your web development career by gaining exposure to productive tactics in Codeigniter.

In this CodeIgniter 4 file upload validation example, we will begin from starting till the end and throw light on every aspect, which is nesseccary and significant to build this essential functionality.

We will add the file size validation and file type validation to the image; accordingly, if your image passes this validation, it will only be stored in the database and locally on the uploads folder.

CodeIgniter 4 Image/File Upload with Validation Example

  • Step 1: Create New Codeigniter Project
  • Step 2: Connect App to Database
  • Step 3: Generarte Table in Database
  • Step 4: Add New Route
  • Step 5: Add File Upload Logic in Controller
  • Step 6: Build Image Upload View File
  • Step 7: Test Application in Browser

Create New Codeigniter Project

Start with installing the brand new Codeigniter app, make sure that Composer is installed.

If you don’t like that and wants a shorter way to download the Codeigniter app, so install it from the Codeigniter site.

composer create-project codeigniter4/appstarter

Connect App to Database

There are many other ways to make the DB connection, but adding the DB values in app/Config/Database.php is the best way to connect the Codeigniter app to the database.

public $default = [
        'DSN'      => '',
        'hostname' => 'localhost',
        'username' => 'db_username',
        'password' => 'db_password',
        'database' => 'db_name',
        '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,
    ];

Generate Table in Database

A table is a container for the data you will store after uploading an image from the Codeigniter platform. It will hold all the images. Go to your database select the database you want to generate the table for.

Execute the given SQL command to form the table.

CREATE TABLE profile (
    id int(11) NOT NULL AUTO_INCREMENT COMMENT 'Primary Key',
    file_name varchar(100) NOT NULL COMMENT 'File Name',
    file_type varchar(255) NOT NULL COMMENT 'File Type',
    PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='file upload demo table' AUTO_INCREMENT=1;

Add New Route

We are about to tell you how to register the new route; this route will initialize the controller function.

Update app/Config/Routes.php file.

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

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

Create Image Upload Controller

Now you will learn exactly how to create a controller file and define the logic to show file upload template and methods to validate image file before upload and store the image after upload in the database.

Update app/Controllers/ImageUploadController.php file.

<?php 

namespace App\Controllers;

use CodeIgniter\Controller;


class ImageUploadController extends Controller
{

    public function index() 
	{
        return view('index');
    }

    function uploadImage() { 
        
        helper(['form', 'url']);

        $database = \Config\Database::connect();
        $db = $database->table('profile');
    
        $file = $this->validate([
            'file' => [
                'uploaded[file]',
                'mime_in[file, image/png, image/jpg, image/jpeg]',
                'max_size[file,4096]',
            ]
        ]);
    
        if (!$file) {
            print_r('Wrong file type selected');
        } else {
            $imageFile = $this->request->getFile('file');
            $imageFile->move(WRITEPATH . 'uploads');
    
            $data = [
               'ile_name' =>  $imageFile->getName(),
               'file_type'  => $imageFile->getClientMimeType()
            ];
    
            $save = $db->insert($data);
            print_r('Image uploaded correctly!');        
        }

    }
 
}

Build Image Upload View File

So far, all the mildly complex steps have been taken; now, carefully head over to the app/Views directory, create the index.php file and implement the whole provided code into the view file.

Update app/Views/index.php file.

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

<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">

	<title>CodeIgniter 4 Image Upload with File Validation Example</title>

	<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
	<style>
		.container {
			max-width: 400px;
			margin-top: 50px;
		}
	</style>
</head>

<body>
	<div class="container">


		<form action="<?php echo base_url('ImageUploadController/uploadImage');?>" method="post" enctype="multipart/form-data">
			<div class="form-group mb-3">
				<input name="file" type="file" class="form-control" accept="image/*">
			</div>

			<div class="form-group">
				<button type="submit" class="btn btn-dark">Submit</button>
			</div>
		</form>


	</div>
</body>


</html>

The following view file has the form component with the file input element; bootstrap beautifies the form. The form makes the request using the function defined in the controller.

It is altogether validating the image file, like file size (max upto 4 MB) and image file type.

Test Application in Browser

You no longer have to wait for long to start the app and view the app in the browser.

Let us break the ice and execute the provided command from the command prompt.

php spark serve
http://localhost:8080/upload-image

If you haven’t missed anything and placed everything as instructed, then check the uploads folder. Here you will see the pile of uploaded images similarly in the database.

Image upload and upload validation in Codeigniter

Conclusion

Throughout this small and swift tutorial, you have found a way to build files and image upload with validation in the Codeigniter application. You have seen the pragmatic approaches to apply server-side validation to the image upload module.

We are utterly sure this tutorial will help you strengthen your command over Codeigniter plus database altogether.