Multiple Files Upload in CodeIgniter 4 Tutorial

Share this Article
Reading Time: 6 minutes
1,900 Views

Inside this article we will the concept of multiple files upload in CodeIgniter 4. We can upload any number and any extension type of file.

This tutorial is totally from scratch and step by step guide to complete. Multiple files upload functionality is very common feature in several admin panels of web application. The provided code here will give you the complete concept of multiple files upload in codeigniter 4.

Note*: For this article, CodeIgniter v4.1 setup has been installed. May be when you are seeing, version will be updated. CodeIgniter 4.x still is in development mode.

x
Multiple Files Upload in CodeIgniter 4 Tutorial

Let’s get started.


Download & Install CodeIgniter 4 Setup

We need to download & install CodeIgniter 4 application setup to system.

To set application we have multiple options to proceed.

Here are the following ways to download and install CodeIgniter 4 –

  • Manual Download
  • Composer Installation
  • Clone Github repository of CodeIgniter 4

Complete introduction of CodeIgniter 4 basics – Click here to go. After going through this article you can easily download & install setup.

Here is the command to install via composer –

$ composer create-project codeigniter4/appstarter codeigniter-4

Assuming you have successfully installed application into your local system.


Turn Development Mode On

When we install CodeIgniter 4, we have env file at root. To use the environment variables means using variables at global scope we need to do env to .env

Open project in terminal

$ cp env .env

Above command will create a copy of env file to .env file. Now we are ready to use environment variables.

CodeIgniter starts up in production mode by default. Let’s do it in development mode. So that while working if we get any error then error will show up.

# CI_ENVIRONMENT = production

 // Do it to 
 
CI_ENVIRONMENT = development

Now application is in development mode.


Create Database & Table in Application

To create a database, either we can create via Manual tool of PhpMyadmin or by means of a mysql command.

CREATE DATABASE codeigniter4_app;

Next, we need a table. That table will be responsible to store data. Let’s create table with some columns.

CREATE TABLE `files` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `name` varchar(120) DEFAULT NULL,
 `type` varchar(10) NOT NULL,
 `path` varchar(120) DEFAULT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1

Successfully, we have created a database and a table. Let’s connect with the application.


Database Connectivity to Application

Open .env file from project root. Search for DATABASE. You should see the connection environment variables.

Let’s set the value for those to connect with database.

 
#--------------------------------------------------------------------
# DATABASE
#-------------------------------------------------------------------- 
 database.default.hostname = localhost
 database.default.database = codeigniter4_app
 database.default.username = root
 database.default.password = root
 database.default.DBDriver = MySQLi
   

Now, database successfully connected with application.


Create Route

Open Routes.php from /app/Config folder. Add these routes into it.

//...

$routes->get("upload-files", "SiteController::index");
$routes->post("save-files", "SiteController::saveFiles");

Create Controller

Open project into terminal and run this given spark command to create controller.

$ php spark make:controller Site --suffix

It will create a file SiteController.php inside /app/Controllers folder. Open SiteController.php and write this following code into it.

<?php

namespace App\Controllers;

use App\Controllers\BaseController;

class SiteController extends BaseController
{
	public function __construct()
	{
		$this->db = db_connect();
	}

	public function index()
	{
		return view("upload-files");
	}

	public function saveFiles()
	{
		$builder = $this->db->table('files');

		$session = session();

		if ($this->request->getFileMultiple('file')) {

			foreach ($this->request->getFileMultiple('file') as $file) {

				$file->move('uploads');

				$data = [
					'name' =>  $file->getClientName(),
					'type'  => $file->getClientMimeType(),
					'path' => 'uploads/' . $file->getClientName()
				];

				$builder->insert($data);
			}

			$session->setFlashdata("success", "Files uploaded");
		} else {

			$session->setFlashdata("error", "Please choose file");
		}

		return redirect()->to("upload-files");
	}
}
  • $this->db = db_connect(); This is for creating database instance.
  • $this->db->table(‘files’); Loading files table by query builder of codeigniter 4.
  • $session = session(); Creating a session instance
  • $this->request->getFileMultiple(‘file’); Get multi files from request.
  • $file->move(‘uploads’); Uploading file to /public/uploads folder.
  • $file->getClientName() Get File name
  • $file->getClientMimeType() Get file extension type
  • $builder->insert($data); Insert data into table using query builder
  • $session->setFlashdata(“success”, “Files uploaded”); Setting flash message into session
  • return redirect()->to(“upload-files”); Redirecting to the given route after processing request.

When we upload file, automatically application will create a /uploads folder inside /public folder if it doesn’t exists.


Create View File

Create upload-files.php at /app/Views folder. Open this layout file and write this code.

<!DOCTYPE html>
<html>
<head>
  <title>Codeigniter 4 Multiple Files Upload Example</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
 
</head>
<body>
 <div class="container" style="margin-top: 30px;">
   <h3>Codeigniter 4 Multiple Files Upload</h3>
    <br>
     
    <?php if (session('error')) : ?>
        <div class="alert alert-danger alert-dismissible">
            <?= session('error') ?>
            <button type="button" class="close" data-dismiss="alert"><span>×</span></button>
        </div>
    <?php endif ?>

    <?php if (session('success')) : ?>
        <div class="alert alert-success alert-dismissible">
            <?= session('success') ?>
            <button type="button" class="close" data-dismiss="alert"><span>×</span></button>
        </div>
    <?php endif ?>
 
    <div class="row">
      <div class="col-md-9">

        <form method="post" enctype="multipart/form-data" action="<?php echo base_url('save-files');?>">
 
          <div class="form-group">
            <label for="formGroupExampleInput">Select Files</label>
            <input type="file" name="file[]" class="form-control" multiple>
          </div> 
 
          <div class="form-group">
           <button type="submit" class="btn btn-success">Submit</button>
          </div>
          
        </form>
      </div>
    </div>
</div>
</body>
</html>

Application Testing

Start development server:

$ php spark serve

URL: http://localhost:8080/upload-files

When we select multiple files from system by pressing Ctrl + Mouse Click, upload it. We can see into this image, we have saved all types of extension files into database.

We hope this article helped you for multiple files upload in CodeIgniter 4 Tutorial in a very detailed way.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Find More on CodeIgniter 4 here