When you want to upload image in Codeigniter 4, you have to take care of the validation. Without proper validation, file upload is not secure for SQL injection. Someone might do the SQL injection with the file upload. Hence, it is very important to prevent code injection through the file upload. In Codeigniter, you can validate the image or file before uploading it. You can check the mime type, size, file extension, etc. These are the property of the file. So, by using these properties, you can validate the file properly. After the validation, the image will be moved to the specified directory. Also, we will save the filename into the database. In this post, I will show you how you can upload image in Codeigniter 4 from very scratch. So, let’s begin by creating a new project.
Prerequisites
If you are going to create a new project in Codeigniter 4 the you must install the below tools.
- PHP >= 7.3
- MySQL (version > 5)
- Apache/Nginx Server
- VS Code Editor
- Composer
Create a Project to Upload Image in Codeigniter
To start with a new project, I will be using composer. You have to open the terminal and hit the below command.
composer create-project codeigniter4/appstarter form-validation
It will create a new project inside the specified directory.
After creating the project, it is required to connect it with a database. Hence, in the next step, we will create a database in MySQL.
Form Validation Example in Codeigniter 4 For Beginners
Create and Configure Database
For the database management, I am using MySQL. Hence, I have created a database by using the below command.
CREATE DATABASE ci4_form;
Once, you created the database, let’s come back to the project folder. Now, open it inside the editor. Here, we will configure the database credentials.
- In the step 1, rename the env file to .env file.
- Next, you have to change the environment to development. By default, it is production.
- Now, go to the database section 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, we connected the database successfully with the Codeigniter 4 application.
How to Upload Image in Laravel 8 with Validation
Create Migration For Image Table
In this post, we will validate the image before uploading. But, if the validation is succeed then we will insert the image name into the database. Hence, you will require to create a migration file. So, we will be creating the migration file using the spark command.
php spark make:migration images --table
The above command will create a migration file for the images table.
After creating the migration file, let’s add some fields there. The field will create the schema of the table.
<?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 migration file, I have added the necessary fields. You can add more if you want. After that, it will require to migrate into the database.
php spark migrate
The above command will migrate the table into the database. After the successful migration, you will be able to see the schema of the tables inside the database.
Create a CRUD Application in CodeIgniter 4 For Beginners
Create Model to Upload Image in Codeigniter 4
We will insert the image name into the table using the Model. Hence, you required a model for the Image. The below command will create a Model class.
php spark make:model Image
Here, you have the model. Now, the model requires to have the allowed fields. The allowed fields property determines the fields which will be inserted.
So, let’s put the fields in the Image model.
<?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';
}
Now, we have to implement the functionality to upload image in Codeigniter 4.
How to Install CodeIgniter 4 in Windows and Linux
Create a Controller to Upload Image in Codeigniter 4
For Image validation and uploading, you will require to write the validation rules. So, create a controller first then we will write the validation rules inside it.
php spark make:controller ImageController
The above command will create the controller file.
<?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]',
],
]);
if (!$validated) {
return view('upload', [
'validation' => $this->validator
]);
}
// Grab the file by name given in HTML form
$file = $this->request->getFile('image');
// Generate a new secure name
$name = $file->getRandomName();
// Move the file to the directory
$file->move('uploads', $name);
$image = new Image;
$image->save([
'name' => $name
]);
session()->setFlashdata('success', 'Success! image uploaded.');
return redirect()->to(site_url('/upload'))->withInput()->with('previewImage', $name);
}
}
After creating the functions in the ImageController, you have to create the routes.
How to Create Github Login in Laravel 8 Using Socialite
Create Routes
You will have to add the below routes in the app/Config/Routes.php file.
$routes->get('upload', 'ImageController::index');
$routes->post('upload', 'ImageController::uploadImage');
After adding the above routes, you have to create a form in which we will take input of file.
Laravel 8 CRUD Application Tutorial From Scratch
Create a View to Upload Image
For creating the view, just go to the app/Views folder. Now, create a file named upload.php. After creating the view, let’s put the below snippet for creating a form with inputs.
<!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"/>
<?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>
<img src="<?php echo base_url('uploads/'.session()->getFlashdata('previewImage'));?>" class="img-fluid" height="200px"/>
</div>
<?php endif; ?>
</div>
</div>
</div>
</div>
</body>
</html>
That’s it for the functionality. Now, you can check the result by running the application using php spark command. For more details, you can visit the official documentation of Codeigniter 4.
Laravel 8 Form Validation Tutorial For Beginners
Check the Image Upload Result in Codeigniter 4
Run the Codeigniter 4 project using the below command.
php spark serve
The above command will start the codeigniter development server on the default port.
Now, redirect to the specified route that is http://localhost:8080/upload
. You will have the below result that is a form with input of file and a button.
When you try to submit the form without any file, it will throw the validation error message as showing below.
Now, try to select any other file format apart from image. Here, I have selected a .zip file to check whether the validation is working properly.
In the result of upload attempt, it hasn’t allowed the other file type apart from image.
Now, I tried the upload with a valid image that is a mime type image and extension is .png.
In the response of upload attempt, I got the success. It means, image has been uploaded successfully. Also, the uploaded image has shown in the form of preview.
After the uploading, the image name will be inserted into the database table. Let me show you the table. Here, I have uploaded two images one by one.
Conclusion
Bingo! we implemented the functionality to upload image in Codeigniter 4. We did the validation for the image so that it will accept only image. You can set the other validation for the file type. In this post, I just shown the validation for the mime type image only. Similarly, it will for the document format. I hope you won’t face any issue on this post. Keep coding.
Leave a Reply