By creating an array of images, you can upload multiple image in Codeigniter 4. The HTML element of file type has an attribute to accept multiple files. The input element of file type requires the name attribute to be an array. We already know about an array in PHP. It can store multiple items in a single variable name. The Codeigniter provides some predefined functions to read out single and multiple files. You can validate the file mime types, size, etc. It is the most important part of a file upload to validate it properly. I already shared the post on Image upload with validation in Codeigniter 4. But, in this post, I will upload multiple image in Codeigniter 4 with validation. So, you will learn to pass multiple image through the form. Also, validation of image and upload. So, let’s move to the post quickly.
Prerequisites
For creating this project in Codeigniter 4, your system must have the below requirements.
- PHP >= 7.3
- MySQL (version > 5)
- Apache/Nginx Server
- VS Code Editor
- Composer
Create a Project to Upload Image in Codeigniter 4
To create a new project in Codeigniter 4, I will be using composer. Open the terminal and hit the below command.
composer create-project codeigniter4/appstarter form-validation
The above command will create a new folder. Then inside that folder the codeigniter 4 will be installed.
After creating the project, let’s have a database configuration for this project.
Form Validation Example in Codeigniter 4 For Beginners
Create and Configure Database
For managing the database, I am using MySQL. Therefore, I have created a database by hitting the below command.
CREATE DATABASE ci4_form;
Now, we have the database ready. Let’s connect it to the Codeigniter 4 project.
- Firstly, rename the env file to the .env file.
- Secondly, open the .env file and change the environment to development. By default, it is production.
- Lastly, go to the database section inside this file and replace the credentials as showing below.
#--------------------------------------------------------------------
# DATABASE
#--------------------------------------------------------------------
database.default.hostname = localhost
database.default.database = ci4_form
database.default.username = root
database.default.password = root
database.default.DBDriver = MySQLi
Now, you configured successfully the database with project.
Create Migration For Image Table
In this project, we will see multiple image validation. After the successful validation, we will upload multiple image. Lastly, we will store the uploaded image name into the database table. Hence, we required a migration. You can create a table and its schema manually through the database. But, I prefer to create it using migration.
php spark make:migration images --table
After hitting the above command, it will create a migration file for image table.
You can check the file inside the Database/Migrations folder.
Here, we will create the schema for the image table. Hence, in the up() function, we will add some fields.
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class Images extends Migration
{
public function up()
{
$this->forge->addField([
'id' => [
'type' => 'INT',
'auto_increment' => true
],
'name' => [
'type' => 'VARCHAR',
'constraint' => '255'
],
'created_at datetime default current_timestamp',
'updated_at datetime default current_timestamp on update current_timestamp'
]);
$this->forge->addKey('id', true);
$this->forge->createTable('images');
}
public function down()
{
$this->forge->dropTable('images');
}
}
In the above snippet, we have the schema for creating the image table. Also, the table can be deleted with the same migration file.
Now, you have to migrate the schema into the database. Hence, hit the below command.
php spark migrate
The above command will generate the schema for the image table inside the database.
Create a CRUD Application in CodeIgniter 4 For Beginners
Create a Model to Upload Multiple Image in Codeigniter 4
If you are thinking to create a model in Codeigniter then no need to create a new model file manually. Codeigniter 4 provides spark to create model. Hence, we will create a model using the below command.
php spark make:model Image
Through this model, we will store the multiple uploaded image into the database table.
Now, go to the model file and make it to look as showing below.
<?php
namespace App\Models;
use CodeIgniter\Model;
class Image extends Model
{
protected $DBGroup = 'default';
protected $table = 'images';
protected $primaryKey = 'id';
protected $useAutoIncrement = true;
protected $protectFields = true;
protected $allowedFields = ['name'];
// Dates
protected $useTimestamps = false;
protected $dateFormat = 'datetime';
protected $createdField = 'created_at';
protected $updatedField = 'updated_at';
}
In the next step, we will have to implement the functionality to upload multiple image. Hence, it required a controller file to write the logic.
How to Create Github Login in Laravel 8 Using Socialite
Create a Controller to Upload Multiple Image in Codeigniter 4
For creating the controller, we will use the same approach. Here, the spark will create a controller also. So, hit the below command in the terminal.
php spark make:controller ImageController
The above command will create a controller with the name ImageController.php.
After creating the controller file, let’s put the below snippet there.
<?php
namespace App\Controllers;
use App\Controllers\BaseController;
use App\Models\Image;
class ImageController extends BaseController
{
/**
* Constructor
*/
public function __construct()
{
helper(['form', 'url']);
}
/**
* Return image upload view
*
* @return void
*/
public function index()
{
return view('upload');
}
/**
* Upload Image
*
* @return void
*/
public function uploadImage()
{
// image validation
$validated = $this->validate([
'image' => [
'uploaded[image]',
'mime_in[image,image/jpg,image/jpeg,image/gif,image/png]',
'max_size[image,4096]',
'errors' => [
'uploaded[image' => 'Please select an image.'
]
],
]);
if (!$validated) {
return view('upload', [
'validation' => $this->validator
]);
}
// Grab the file by name given in HTML form
$files = $this->request->getFileMultiple('image');
$filePreviewName = [];
foreach($files as $file) {
if($file->isValid() && !$file->hasMoved()) {
$newName = $file->getRandomName();
$file->move('uploads', $newName);
$image = new Image;
$image->save([
'name' => $newName
]);
array_push($filePreviewName, $newName);
}
}
session()->setFlashdata('success', 'Success! image uploaded.');
return redirect()->to(site_url('/upload'))->withInput()->with('previewImage', $filePreviewName);
}
}
Now, you have to create routes as per the above functions respectively.
Laravel 8 Multiple Images Upload with Validation
Create Routes
For creating the routes, you have to navigate to the app/Config/Routes.php file. Hence, add the below routes there.
$routes->get('upload', 'ImageController::index');
$routes->post('upload', 'ImageController::uploadImage');
At last, you have to create a view for uploading the multiple image.
Create View to Upload Multiple Image in Codeigniter 4
To create a view, go to the app/Views folder and create a new file with the name upload.php. After creating the view, put the below snippet there.
<!doctype html>
<html lang="en">
<head>
<title>Codeigniter 4 Form Validation Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- bootstrap 5 CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.4.1/font/bootstrap-icons.css">
</head>
<body>
<div class="container py-4">
<?php $validation = \Config\Services::validation(); ?>
<div class="row">
<div class="col-xl-6 col-lg-6 col-md-6 col-sm-12 col-12 m-auto">
<form method="POST" action="<?= base_url('upload') ?>" enctype="multipart/form-data">
<?= csrf_field() ?>
<!-- display flash data message -->
<?php
if(session()->getFlashdata('success')):?>
<div class="alert alert-success alert-dismissible">
<button type="button" class="btn-close" data-bs-dismiss="alert">×</button>
<?php echo session()->getFlashdata('success') ?>
</div>
<?php elseif(session()->getFlashdata('failed')):?>
<div class="alert alert-danger alert-dismissible">
<button type="button" class="btn-close" data-bs-dismiss="alert">×</button>
<?php echo session()->getFlashdata('failed') ?>
</div>
<?php endif; ?>
<div class="card shadow">
<div class="card-header">
<h5 class="card-title">Upload Image</h5>
</div>
<div class="card-body p-4">
<div class="form-group mb-3 has-validation">
<label class="form-label">Image</label>
<input type="file" class="form-control <?php if($validation->getError('image')): ?>is-invalid<?php endif ?>" name="image[]" multiple="multiple"/>
<?php if ($validation->getError('image')): ?>
<div class="invalid-feedback">
<?= $validation->getError('image') ?>
</div>
<?php endif; ?>
</div>
</div>
<div class="card-footer">
<button type="submit" class="btn btn-primary">Upload</button>
</div>
</div>
</form>
<?php
if(session()->getFlashdata('previewImage')):?>
<div class="form-group py-4">
<h5 class="py-2">Image Preview</h5>
<?php foreach(session()->getFlashdata('previewImage') as $image): ?>
<img src="<?php echo base_url('uploads/'.$image);?>" class="img-fluid" height="150px"/>
<br/>
<br/>
<?php endforeach; ?>
</div>
<?php endif; ?>
</div>
</div>
</div>
</div>
</body>
</html>
The above snippet will create a form with an input of file. The input will accept the multiple files. After submitting the file, it will go to the controller and in the controller we already added the validation. Once, the validation will pass, it will upload the image and store them to the table.
Lastly, the uploaded image will be displayed in the view. So, we stored the images into an array and returned it to view using flash data.
How to Upload Image in Laravel 8 with Validation
Multiple Upload Image Result
Now, it’s time to check the result by uploading multiple images. So, run the Codeigniter 4 project using the spark command.
php spark serve
The above command will start the CodeIgniter development server.
Just open the URL in your browser and navigate to upload URL as showing below.
As per the validation rules that we already set, you will get the below result for required field. Here, I have not selected any file and clicked on upload. It returned the validation error message.
Now, for the testing, I have selected a .zip file. But, we have set the validation for accepting file type image only.
In the result, you can see, it didn’t allow to upload the other mime type file. It returned back with the validation error message of mime type.
Now, at last, I have chosen the multiple images as you can and clicked on the upload button.
In the final result, you can see, the images are uploaded. We have the preview of every images in the below result also.
Conclusion
We completed the multiple image upload functionality in CodeIgniter 4. You can set the other validation for accepting the different file type. Similarly, you can upload doc, xls, pdf, etc. I will show you one by one on the upcoming posts. If you get any issue in the above post then don’t forget to ask through the comment. I feel happy to response you on your query.
sandi says
Sir Can you post a program where “Upload Multiple Image with Validation in CodeIgniter 4 using ajax”