Image Upload with Form data in CodeIgniter 4 Tutorial

Share this Article
Reading Time: 11 minutes
5,383 Views

Submitting form data, uploading any type of file is a common work for every application. Inside this article we will see the concept of Image upload with Form data in CodeIgniter 4.

We will see how can we upload an image file in CodeIgniter with few form validation rules to validate file upload and it’s type.

This article gives you the complete concept of File upload in codeigniter 4. Step by step guide and surely it will be very interesting to learn and implement.

Learn More –

  • CodeIgniter 4 Form Data Submit by Ajax Method, 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 – Image file upload with Form in CodeIgniter 4.


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.


CodeIgniter 4 File Upload

File management in web applications is a common essential. If we are working where we manages content, then we will work with form data, file uploads, upload type – document, pdfs, text files etc.

In CodeIgniter 4, file upload as well as form data upload is pretty simply due to availability of core libraries.

Here, inside this article we will create a Controller, Model, View file & use it’s core request library to upload.

First of all let’s configure application – Create Database, Table & it’s columns to store data.


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 `tbl_users` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `name` varchar(120) DEFAULT NULL,
 `email` varchar(120) DEFAULT NULL,
 `phone_no` varchar(120) DEFAULT NULL,
 `profile_image` varchar(180) DEFAULT NULL,
 `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Now, we need to create Route, a Controller, View template.


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.


Add Routes

Open Routes.php from /app/Config folder. Add this route into it.

//...

$routes->match(["get", "post"], "my-form", "User::myForm");

Create Model

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

$ php spark make:model User --suffix

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

<?php

namespace App\Models;

use CodeIgniter\Model;

class UserModel extends Model
{
	protected $DBGroup              = 'default';
	protected $table                = 'tbl_users';
	protected $primaryKey           = 'id';
	protected $useAutoIncrement     = true;
	protected $insertID             = 0;
	protected $returnType           = 'array';
	protected $useSoftDelete        = false;
	protected $protectFields        = true;
	protected $allowedFields        = [
      'name', 
      'email', 
      'phone_no', 
      'profile_image'
    ];

	// 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          = [];
}

Model is pointing tbl_users table. We have specified all the table columns into $allowedFields. If suppose we don’t specify then it restrict mass assignment to those columns.


Create View Layout File

As, we have taken fields as name, email, phone_no, profile_image. So with respective with these fields we need to set the user layout.

Create my-form.php inside /app/Views folder

Inside this view file, at top header we have used session() service to collect session temporary data to show flash message. Flash message will be send from controller in keys of success and error.

<!DOCTYPE html>
<html lang="en">
<head>
  
  <title>Image Upload with Form data in CodeIgniter 4 Tutorial</title>
  
</head>
<body>

   <?php
  if(session()->get("success")){
    ?>
      <h3><?= session()->get("success") ?></h3>
    <?php
  }
  if(session()->get("error")){
    ?>
    <h3><?= session()->get("error") ?></h3>
    <?php
  }
?>

<form action="<?= site_url('my-form') ?>" method="post" enctype="multipart/form-data">
   <p>
       Name: <input type="text" name="name" placeholder="Enter name"/>
   </p>

   <p>
       Email: <input type="email" name="email" placeholder="Enter email"/>
   </p>

   <p>
       Phone No: <input type="text" name="phone_no" placeholder="Enter phone"/>
   </p>

   <p>
     File Upload: <input type="file" name="profile_image"/>
   </p>
   <p>
     <button type="submit">Submit</button>
   </p>
</form>

</body>
</html>
  • if(session()->get(“success”)){} – Checking for success key of temporary stored message.
  • session()->get(“success”) – Print session flash – success key message
  • if(session()->get(“error”)){} – Checking for success key of temporary stored message.
  • session()->get(“error”) – Print session flash – error key message
  • site_url(‘my-form’) – Site URL with my-form route
  • enctype=”multipart/form-data” – Multipart form data with image upload function

Create Controller

Create a “images” folder inside /public folder.

Inside this folder we will save uploaded image. Please make sure this images folder should have the sufficient permission to store file.

$ php spark make:controller User

It will creates User.php file at /app/Controllers folder.

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

Manual Form Validations

<?php

namespace App\Controllers;

use App\Models\UserModel;

class User extends BaseController
{
    public function myForm()
    {
        if ($this->request->getMethod() == "post") {

            $file = $this->request->getFile("profile_image");

            $file_type = $file->getClientMimeType();

            $valid_file_types = array("image/png", "image/jpeg", "image/jpg");

            $session = session();

            if (in_array($file_type, $valid_file_types)) {

                $profile_image = $file->getName();
              
              	// We can also use it like this. Automatically move function place the default image name into specified location.
                // Second value will be more beneficiary when we want to give a different name to the uploaded file.
                // $file->move("images"); 

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

                    $userModel = new UserModel();

                    $data = [
                        "name" => $this->request->getVar("name"),
                        "email" => $this->request->getVar("email"),
                        "phone_no" => $this->request->getVar("phone_no"),
                        "profile_image" => "/images/" . $profile_image,
                    ];

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

                        $session->setFlashdata("success", "Data saved successfully");
                    }else{

                        $session->setFlashdata("error", "Failed to save data");
                    }
                } else {
                    $session->setFlashdata("error", "Failed to move file");
                }
            } else {
                // invalid file type
                $session->setFlashdata("error", "Invalid file type selected");
            }

            return redirect()->to(base_url());

        }

        return view("my-form");
    }
}
  • if ($this->request->getMethod() == “post”) {} Checking method type of request.
  • $this->request->getFile(“profile_image”) – Reading file from requested parameters
  • $file_type = $file->getClientMimeType(); This is used to get File MIME type, which we use to check uploaded file type and do a specific code for validating Image file only.
  • $profile_image = $file->getName(); This will return the Image file name what we will upload.
  • $file->move(“images”) We can also use it as here. The second value when we want to change the name to something different name.
  • $file->move(“images”, $profile_image) move() method is used to upload the image from form to images folder.
  • $session->setFlashdata(“success”, “Data saved successfully”); – Storing success message in session flash
  • $session->setFlashdata(“error”, “Invalid file type selected”); – Storing error message in session flash.

Add Form Validations

In the above controller method, we are not using form validation rules. Let’s apply some form validations which is default provided by CodeIgniter 4.

We will add several rules according to the used input fields. Have a look updated myform() method of above Controller.

# Method to submit form

public function myForm()
{
  if ($this->request->getMethod() == "post") {

    $rules = [
      "name" => "required|min_length[3]|max_length[40]",
      "email" => "required|valid_email",
      "phone_no" => "required|min_length[9]|max_length[15]",
      "profile_image" => [
        "rules" => "uploaded[profile_image]|max_size[profile_image,1024]|is_image[profile_image]|mime_in[profile_image,image/jpg,image/jpeg,image/gif,image/png]",
        "label" => "Profile Image",
      ],
    ];

    if (!$this->validate($rules)) {

      return view("my-form", [
        "validation" => $this->validator,
      ]);
    } else {

      $file = $this->request->getFile("profile_image");

      $session = session();
      $profile_image = $file->getName();

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

        $userModel = new UserModel();

        $data = [
          "name" => $this->request->getVar("name"),
          "email" => $this->request->getVar("email"),
          "phone_no" => $this->request->getVar("phone_no"),
          "profile_image" => "/images/" . $profile_image,
        ];

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

          $session->setFlashdata("success", "Data saved successfully");
        } else {

          $session->setFlashdata("error", "Failed to save data");
        }
      }
    }
    return redirect()->to(base_url());
  }
  return view("my-form");
}
  • $rules = []; This contains all rules we have applied over input fields. Rules contains like required, for minimum length, for maximum length, valid email and for different different cases of uploaded file.
  • uploaded[profile_image], mime_in[profile_image,…], max_size[profile_image,4096] Here inside these file uploaded rules we have to pass the name attribute as first value of list.
  • if (!$this->validate($rules)) {} Validating input field values with specified rules.

In view file, to receive validation error messages we need to add the following line of of code.

<?php  
    // To print error messages
  if(isset($validation)){
    
    print_r($validation->listErrors() );
  }
?>

Application Testing

Start development server:

$ php spark serve

URL: http://localhost:8080/my-form

To learn more about Form Validation in CodeIgniter 4, Click here.

We hope this article helped you to learn about CodeIgniter 4 Image Upload with Form data in a very detailed way.

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

1 thought on “Image Upload with Form data in CodeIgniter 4 Tutorial”

Comments are closed.