Upload Image by REST API in CodeIgniter 4 Tutorial

Share this Article
Reading Time: 9 minutes
2,960 Views

CodeIgniter 4 is an open source framework of PHP. There are several libraries available in codeigniter 4 which makes application development very easy.

Inside this article we will see the concept of Upload image by REST API in CodeIgniter 4. Uploading image or file using REST API is bit confusion for all developers. But when you complete this article and it’s steps, Surely you will be able to upload an image in rest api using CodeIgniter 4.

If you want to do this upload in case of Update function, you need to use the concept of Method spoofing in CodeIgniter 4. HTTP Method Spoofing is used to complete the HTTP verbs like PUT and DELETE. Browser provides the HTTP methods to process the action by using GET and POST method, they don’t allow to submit the request using PUT, PATCH & DELETE.

Article is very interesting to learn and super easy to implement. We will use POST request with form data parameters.

Learn more –

  • CodeIgniter 4 RESTful APIs with JWT Authentication, Click here.
  • REST API Development with Validation in CodeIgniter 4, Click here.
  • Basic Auth REST API Development in CodeIgniter 4, Click here.

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.

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,
 `file_name` varchar(120) DEFAULT NULL,
 `file_path` varchar(220) DEFAULT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Successfully, we have created a database and a table.


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 Model

Back to terminal and run this spark command to create a model file.

$ php spark make:model File --suffix

It will create FileModel.php file at /app/Models folder. Open file and write this complete code into it.

<?php

namespace App\Models;

use CodeIgniter\Model;

class FileModel extends Model
{
	protected $DBGroup              = 'default';
	protected $table                = 'files';
	protected $primaryKey           = 'id';
	protected $useAutoIncrement     = true;
	protected $insertID             = 0;
	protected $returnType           = 'array';
	protected $useSoftDelete        = false;
	protected $protectFields        = true;
	protected $allowedFields        = [
		"file_name", 
		"file_path"
	];

	// Dates
	protected $useTimestamps        = false;
	protected $dateFormat           = 'datetime';
	protected $createdField         = 'created_at';
	protected $updatedField         = 'updated_at';
	protected $deletedField         = 'deleted_at';

	// Validation
	protected $validationRules      = [];
	protected $validationMessages   = [];
	protected $skipValidation       = false;
	protected $cleanValidationRules = true;

	// Callbacks
	protected $allowCallbacks       = true;
	protected $beforeInsert         = [];
	protected $afterInsert          = [];
	protected $beforeUpdate         = [];
	protected $afterUpdate          = [];
	protected $beforeFind           = [];
	protected $afterFind            = [];
	protected $beforeDelete         = [];
	protected $afterDelete          = [];
}

Create Controller

Open project into terminal and run this spark command.

$ php spark make:controller Api/Api --suffix --restful

It will create ApiController.php file inside /app/Controllers/Api folder. Along with controller it will also create a folder.

Open ApiController.php and write this complete code into it.

<?php

namespace App\Controllers\Api;

use CodeIgniter\RESTful\ResourceController;
use App\Models\FileModel;

class ApiController extends ResourceController
{
	public function uploadImage()
	{
		$file = $this->request->getFile('image');

		$profile_image = $file->getName();

		// Renaming file before upload
		$temp = explode(".",$profile_image);
		$newfilename = round(microtime(true)) . '.' . end($temp);

		if ($file->move("images", $newfilename)) {

			$fileModel = new FileModel();

			$data = [
				"file_name" => $newfilename,
				"file_path" => "/images/" . $newfilename
			];

			if ($fileModel->insert($data)) {

				$response = [
					'status' => 200,
					'error' => false,
					'message' => 'File uploaded successfully',
					'data' => []
				];
			} else {

				$response = [
					'status' => 500,
					'error' => true,
					'message' => 'Failed to save image',
					'data' => []
				];
			}
		} else {

			$response = [
				'status' => 500,
				'error' => true,
				'message' => 'Failed to upload image',
				'data' => []
			];
		}

		return $this->respondCreated($response);
	}

	public function listImages()
	{
		$fileModel = new FileModel();

		$response = [
			'status' => 200,
			"error" => false,
			'messages' => 'Files list',
			'data' => $fileModel->findAll()
		];

		return $this->respondCreated($response);
	}
}

We have only upload file and list file apis. But you can do other apis as well like update and delete.


How To Upload & Process Image When Update?

When we upload form data it always process using GET & POST request type. It don’t able to response PUT & Delete requests. So how can we process now update and delete functions?

HTTP Method Spoofing is used to complete the HTTP verbs like PUT and DELETE. Browser provides the HTTP methods to process the action by using GET and POST method, they don’t allow to submit the request using PUT, PATCH & DELETE.

Click here to learn about complete guide for HTTP Method Spoofing in CodeIgniter 4.

Route

$routes->put("update-image", "ApiController::updateImage");

Controller Method

public function updateImage()
{ 
         //... do your logic

        $response = [
            'status' => 200,
            "error" => false,
            'messages' => 'Update Image Method',
            'data' => []
        ];

        return $this->respondCreated($response);
}

File Upload

When we will do file upload, need to add an extra value i.e _method = PUT. It will complete your HTTP PUT request process.


Add Routes

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

//...

 $routes->group("api", ["namespace" => "App\Controllers\Api"] , function($routes){

	 $routes->post("upload-image", "ApiController::uploadImage");
     $routes->get("list-images", "ApiController::listImages"); 
});

//...

Application Testing

Start development server:

$ php spark serve

UPLOAD IMAGE API

URL: http://localhost:8080/api/upload-image

METHOD: POST

FORM DATA:

image: <FileType>

HANDLER: \App\Controllers\Api\ApiController::uploadImage

LIST IMAGES API

URL: http://localhost:8080/api/list-images

METHOD: GET

HANDLER: \App\Controllers\Api\ApiController::listImages

Database Table

We hope this article helped you to learn Upload Image by REST API in CodeIgniter 4 Tutorial in a very detailed way.

Buy Me a Coffee

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