Image Upload with Form data in CodeIgniter 4 Tutorial

Share this Article
Reading Time: 11 minutes
13,674 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 –

Let’s get started – Image file upload with Form in CodeIgniter 4.


CodeIgniter 4 Installation

To create a CodeIgniter 4 setup run this given command into your shell or terminal. Please make sure composer should be installed.

$ composer create-project codeigniter4/appstarter codeigniter-4

Assuming you have successfully installed application into your local system.


Environment (.env) Setup

When we install CodeIgniter 4, we will have env file at root. To use the environment variables means using variables at global scope we need to do env to .env

Either we can do via renaming file as simple as that. Also we can do by terminal command.

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.

Enable Development Mode

CodeIgniter starts up in production mode by default. You need to make it in development mode to see any error if you are working with application.

Open .env file from root.

# 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

To create a database, either we can create via Manual tool of PhpMyadmin or by means of a mysql command.

We will use MySQL command to create database. Run this command into Sql tab of PhpMyAdmin.

CREATE DATABASE codeigniter4_app;

Successfully, we have created a database.


Create Database Table

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 Connection

Open .env file from project root.

Search for DATABASE. You should see the connection environment variables into it. Put your updated details of database connection string.

 
#--------------------------------------------------------------------
# DATABASE
#--------------------------------------------------------------------

database.default.hostname = localhost
database.default.database = codeigniter4_app
database.default.username = root
database.default.password = root
database.default.DBDriver = MySQLi
database.default.DBPrefix =
   

Now, database successfully connected with the 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

Open project terminal and start development server via command:

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

Buy Me a Coffee

Online Web Tutor invites you to try Skillshare free for 1 month! Learn CakePHP 4, Laravel APIs Development, CodeIgniter 4, Node Js, etc into a depth level. Master the Coding Skills to Become an Expert in Web Development. So, Search your favourite course and enroll now. Click here to join.

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.

Was this post helpful?

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

Comments are closed.

Learn Web Development Courses Risk Free @ $5 only.
Web Development Courses @ $5