In this basic tutorial, we will relentlessly shed light on every step to upload the multiple images and insert files into the database.
Let’s start building multiple images or files uploading system in Codeigniter:
Table of Contents
Install Codeigniter App
This step requires Composer package manger installed on your local development system, Run the below command to install the new CodeIgniter 4 application. Skip this step if you have already installed the applicaiton.
composer create-project codeigniter4/appstarter
Rename the Codeigniter app name, such as codeigniter-multiple-file-upload.
Go inside the project folder.
cd codeigniter-multiple-file-upload
You can also manually download the Codeigniter 4 application, extract the zip folder and rename the CI 4 application folder name codeigniter-multiple-file-upload.
Enable Errors Reporting
Open app/Config/Boot/development.php file and set the display_errors
to 1 instead of 0. Repeat the exact same process in app/Config/Boot/production.php file. This will enable the error reporting feature in your Codeigniter application.
ini_set('display_errors', '1');
Define Database with Table
Head over to PHPMyAdmin, run the given below SQL query to create a database demo
. Generate a table in which we insert the images or files data, name this table users
.
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;
Make Database Connection
To establish the consensus between database and codeigniter app declare the database name, username and password in application/config/database.php file.
public $default = [
'DSN' => '',
'hostname' => 'localhost',
'username' => 'root',
'password' => 'root',
'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 Controller
To write the multiple files uploading feature we need to generate a app/Controllers/UploadMultipleFiles.php. Next, add the following piece of code inside of it.
<?php
namespace App\Controllers;
use CodeIgniter\Controller;
class UploadMultipleFiles extends Controller
{
public function index() {
return view('home');
}
function uploadFiles() {
helper(['form', 'url']);
$database = \Config\Database::connect();
$db = $database->table('users');
$msg = 'Please select a valid files';
if ($this->request->getFileMultiple('images')) {
foreach($this->request->getFileMultiple('images') as $file)
{
$file->move(WRITEPATH . 'uploads');
$data = [
'name' => $file->getClientName(),
'type' => $file->getClientMimeType()
];
$save = $db->insert($data);
$msg = 'Files have been successfully uploaded';
}
}
return redirect()->to( base_url('/') )->with('msg', $msg);
}
}
We have manifested two functions in this file:
index()
– It renders the file uploading form in CI view.uploadFiles()
– This functions helps in uploading the multiple files and images in database.
Create Routes
Go to app/Config/Routes.php file and place the following piece of code, it will open the multiple file uploading component when the application starts .
/*
* --------------------------------------------------------------------
* Route Definitions
* --------------------------------------------------------------------
*/
$routes->get('/', 'UploadMultipleFiles::index');
$routes->match(['get', 'post'], 'UploadMultipleFiles/uploadFiles', 'UploadMultipleFiles::uploadFiles');
Create View
Ultimately, this is the final step of this application. In this step we will create a file uploading form, this will allow users to upload multiple files and gives notification when files successfully uploads to the server.
We are going to take help of Bootstrap UI framework to create the basic layout and file uploading component.
So, create app/Views/home.php file and insert the following code.
<!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>Upload Multiple Files or Images in Codeigniter 4 - 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">
<?php if (session('msg')) : ?>
<div class="alert alert-success mt-3">
<?= session('msg') ?>
</div>
<?php endif ?>
<form method="post" action="<?php echo base_url('UploadMultipleFiles/uploadFiles');?>"
enctype="multipart/form-data">
<div class="form-group mt-3">
<input type="file" name='images[]' multiple="" class="form-control">
</div>
<div class="form-group">
<button type="submit" class="btn btn-danger">Upload</button>
</div>
</form>
</div>
</body>
</html>
Test Application
Run the following command to start the application:
php spark serve
Use the following URL in the browser to upload multiple images and store into the database:
http://localhost:8080
Download the complete code of this tutorial from GitHub.