CodeIgniter 4 Image Upload with Form data

Share this Article
Reading Time: 12 minutes
57 Views

Submitting form data, uploading any type of file is a common work for every application. Inside this article we will work over CodeIgniter 4 Image Upload with Form data. We will see how can we upload a 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.

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.


Settings Environment Variables

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.


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.

Next, we need to create table where will store form data.

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.


Route Configuration

Let’s define a route which is responsible to handle GET & POST HTTP request. GET request is used to open the form into browser & via POST request type we will submit data and save into database.

Add this given route to /app/Config/Routes.php

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

Firstly let’s load url helper at Parent Controller i.e BaseController.php. This file is in /app/Controllers folder.

Search helpers in BaseController and load “url” into helpers.

protected $helpers = [‘url’];

After loading this url helper, we will able to use site_url() and base_url() in Controllers & Views else we should have some error.

Next, we need to configure CodeIgniter 4 Model & Controller to do it in a complete function.


Application Model Settings

We need to create a Model which provides the functional layer of database with Controllers.

$ php spark make:model User --suffix

Above command will create a Model file UserModel.php created at location /app/Models/

<?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.


View File – Create User Form

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.

Views templates will be created inside /app/Views/my-form.php

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.

<?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>
  • 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

Define Controller File Settings

Controller file provides the interaction of User data & database. By using this controllers and CodeIgniter 4 functions we will save form data and upload image file into upload folder and save into database.

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

Above command will create a file User.php inside /app/Controllers folder.

Form Submission without Form Validation Rules

Open User.php and write this code.

<?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 “CodeIgniter 4 Image Upload with Form data”

Leave a Comment