How to Upload Multiple Image / Files in Codeigniter 4 App

Codeigniter 4 Multiple image and files upload tutorial; Yes, we are about to share how to upload multiple images files in the Codeigniter application.

Not just that, we will also share the practical explanation on how to store the images and files in the database and in the local project folder.

This Codeigniter 4 multiple file upload example is a crucial functionality that will amplify and nurture your knowledge regarding Codeigniter development.

To upload multiple images and files in the Codeigniter 4 app, we will use the getFileMultiple() method; this method is helpful and provides a pragmatic approach to get an array of uploaded files with the corresponding name.

The PHP CodeIgniter is a fantastic framework, and we love its uniformity in tackling programming-related issues dynamically. It has made dealing with files so smooth. You can use a form to upload single and multiple images through the form directly.

Codeigniter 4 Multiple File/Image Upload Example

  • Step 1: Download Codeigniter Project
  • Step 2: Create Table in Database with SQL
  • Step 3: Connect App to Database
  • Step 4: Define New Route
  • Step 5: Create Controller File
  • Step 6: Create Multi File Upload View File
  • Step 7: Initialize App in Browser

Download Codeigniter Project

Installing a new Codeigniter app is not that difficult, let us start downloading the newest version of Codeigniter app using the given link.

https://www.codeigniter.com/download

Then, Unzip the package, change the project’s name, and keep Codeigniter files and folder in your server directory.

Or, it can merely be done with single command, make sure to have Composer configured on your computer.

composer create-project codeigniter4/appstarter

Create Table in Database with SQL

Move to PHPMyAdmin, run the SQL command to create a profile table, and also set the properties for the table.

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

Connect App to Database

Go to app/Config/Database.php, define username, password and database name inside the $default property to connect the 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,
    ];

Define New Route

Go to the app/Config/Routes.php file, specify the default controller, and route with get method with the url you want to use to open the app to get a response through the browser.

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

$routes->setDefaultController('MultiUploadController');

$routes->get('/upload-multi-images', 'MultiUploadController::index');

Create Controller File

In this step, you have to create the controller, file and class. This class will access the database table and the multi-file input and manage to upload multiple files.

Add the below code in app/Controllers/MultiUploadController.php.

<?php 

namespace App\Controllers;
use CodeIgniter\Controller;


class MultiUploadController extends Controller
{
    
    public function index() { 
        return view('profile');
    }
    
    function store() {
        helper(['form', 'url']);

        $database = \Config\Database::connect();
        $db = $database->table('profile');

        $alert_message = 'Wrong file selected';

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

            foreach($this->request->getFileMultiple('images') as $file)
            {   
                $file->move(WRITEPATH . 'uploads');
                $data = [
                    'file_name' =>  $file->getClientName(),
                    'file_type'  => $file->getClientMimeType()
                ];

            $store = $db->insert($data);
            $alert_message = 'Files have been successfully uploaded';
            }
        }

        return redirect()->to( base_url('/upload-multi-images') )->with('alert', $alert_message);
    }
 
}

Create Multi File Upload View File

Next, we create the view for multi images upload view file, to build this module we will use the constitute the MultiUploadController/store function in the form action attribute.

Create the file upload element using HTML’s file input property, add name and multiple properties into it.

Create the view file, and add the code in app/Views/profile.php file.

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

<head>
	<meta charset="UTF-8">
	<title>Codeigniter 4 Multi Images Upload Example</title>
	<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
</head>

<body>

	<div class="container">
		<?php if (session('alert')) : ?>
		<div class="alert alert-success mb-3">
			<?= session('alert') ?>
		</div>
		<?php endif ?>

		<form method="post" action="<?php echo base_url('MultiUploadController/store');?>"
			enctype="multipart/form-data">
			<div class="form-group">
				<input type="file" name='images[]' multiple="" class="form-control">
			</div>

			<div class="d-grid mt-2">
				<button type="submit" class="btn btn-dark">Store</button>
			</div>
		</form>
	</div>
</body>

</html>

Initialize App in Browser

Lastly, head over to console, and use the provided command to invoke the development server.

php spark serve

Here is the url that will help you to view and test the app in the browser.

http://localhost:8080/upload-multi-images

How to Upload Multiple Image / Files in Codeigniter App

Conclusion

The options it provides are much simpler and more securer than PHP’s $_FILES array. We believe you have liked this quick guide on Multiple image uploads in CodeIgniter.

Please share your feedback regarding any issue related to the content or create another helpful content in Codeigniter application development.