Codeigniter 4 Image Upload Validation Example

Image upload with validation in CodeIgniter 4. In this example tutorial, i will guide you step by step on how to upload image file with validation in Codeigniter 4 apps using codeigniter 4 build in library.

If you are creating any form with image file upload field in codeigniter 4 app. And want to upload image with validation in codeigniter 4 apps. So, in this tutorial, you will learn how to upload image file with validation in codeigniter 4 apps.

Like you are building any social media, e-commerce web application in codeigniter 4 apps. At that time, Uploading images is a basic requirement in this types of applications. Image file uploading is an important requirement that allows your site visitors to upload various files.

For the CodeIgniter 4 image file upload with validation example , I’ll create a simple form and upload image with validation. And store image into database and codeigniter 4 apps directory.

Codeigniter 4 Image Upload Validation Example

You can learn by following the steps given below on codeIgniter 4 image file upload validation example:

  • Install Codeigniter 4 Application
  • Basic App Configurations
  • Create Database and Table
  • Setup Database Credentials
  • Create Model and Controller
  • Create Views
  • Setup Routes
  • Start Development server

Step 1 – Install Codeigniter 4 Application

First of all, you need to ownload the latest version of Codeigniter 4. So, visit this link https://codeigniter.com/download Download Codeigniter 4 app and unzip the setup in your local system xampp/htdocs/ .

Note that, please change the download folder name “demo”.

Step 2 – Basic App Configurations

Now, you need to some basic configuration on the app/config/app.php file, so let’s go to application/config/config.php and open this file on text editor.

Set Base URL like this

public $baseURL = 'http://localhost:8080';
To
public $baseURL = 'http://localhost/demo/';

Step 3 – Create Database and Table

Create a database and table by executing the following SQL query:

CREATE DATABASE demo;

CREATE TABLE images (
    id int(11) NOT NULL AUTO_INCREMENT COMMENT 'Primary Key',
    name varchar(100) NOT NULL COMMENT 'Name',
    type varchar(255) NOT NULL COMMENT 'file type',
    created_at varchar(20) NOT NULL COMMENT 'Created date',
    PRIMARY KEY (id)
  ) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='demo table' AUTO_INCREMENT=1;

Step 4 – Setup Database Credentials

To connect your codeigniter 4 app to the database. So, visit app/Config/ directory and open Database.php. Then add the databasae details like below into database.php file:

public $default = [
        'DSN'      => '',
        'hostname' => 'localhost',
        'username' => 'test',
        'password' => '4Mu99BhzK8dr4vF1',
        'database' => 'demo',
        'DBDriver' => 'MySQLi',
        'DBPrefix' => '',
        'pConnect' => false,
        'DBDebug'  => (ENVIRONMENT !== 'development'),
        'cacheOn'  => false,
        'cacheDir' => '',
        'charset'  => 'utf8',
        'DBCollat' => 'utf8_general_ci',
        'swapPre'  => '',
        'encrypt'  => false,
        'compress' => false,
        'strictOn' => false,
        'failover' => [],
        'port'     => 3306,
	];

Step 5 – Create Controller

Create FormController.php file. So, visit app/Controllers directory and create FormController.php.Then add the following code into it:

<?php namespace App\Controllers;

use CodeIgniter\Controller;

class FormController extends Controller
{
    public function index()
    {    
         return view('image_form');
    }

   public function store()
   {  

	 helper(['form', 'url']);
        
	 $db      = \Config\Database::connect();
         $builder = $db->table('images');

        $validated = $this->validate([
            'file' => [
                'uploaded[file]',
                'mime_in[file,image/jpg,image/jpeg,image/gif,image/png]',
                'max_size[file,4096]',
            ],
        ]);

        $msg = 'Please select a valid image file';
 
        if ($validated) {
            $avatar = $this->request->getFile('file');
            $avatar->move(WRITEPATH . 'uploads');

          $data = [

            'name' =>  $avatar->getClientName(),
            'type'  => $avatar->getClientMimeType()
          ];

          $save = $builder->insert($data);
          $msg = 'Image has been uploaded';
        }

       return redirect()->to( base_url('form') )->with('msg', $msg);

	}
}

The index() function renders the contact form template into the view.

The store() method handles the form of validation and contains various variables. And store image into db and directory.

Step 6 – Create Views

Create image_form.php view file, so visit application/views/ directory and create image_form.php file. Then add the following HTML into image_form.php file:

<!DOCTYPE html>
<html>
<head>
  <title>Codeigniter 4 Image upload example - Laratutorials.com</title>
 <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">

</head>
<body>
 <div class="container">
    <br>
    
    <?php if (session('msg')) : ?>
        <div class="alert alert-info alert-dismissible">
            <?= session('msg') ?>
            <button type="button" class="close" data-dismiss="alert"><span>×</span></button>
        </div>
    <?php endif ?>

    <div class="row">
      <div class="col-md-9">
        <form action="<?php echo base_url('FormController/store');?>" name="image_upload_form" id="image_upload_form" method="post" accept-charset="utf-8" enctype="multipart/form-data">

          <div class="form-group">
            <label for="formGroupExampleInput">Name</label>
            <input type="file" name="file" class="form-control" id="file">
          </div> 

          <div class="form-group">
           <button type="submit" id="send_form" class="btn btn-success">Submit</button>
          </div>
         
        </form>
      </div>

    </div>
 
</div>
</body>
</html>

Step 7 – Setup Routes

To define a route, So, visit app/Config/ directory and open Routes.php file. Then add the following routes into it:

$routes->setDefaultController('FormController');
$routes->get('/', 'FormController::index');

Note that, the routes will be displaying the image upload form and submitting the data in the database on successful form submission.

Step 8 – Start Development server

Execute the following command into command prompt or terminal to start the codeigniter 4 application:

php spark serve

Then visit your web browser and hit the following url on it:

http://localhost/demo/

OR

http://localhost:8080/

Conclusion

CodeIgniter 4 image upload validation example tutorial. In this example,you have learned how to upload image with validation in Codeigniter 4 apps. And also will learned how to store image into db and directory..

Recommende CodeIgniter 4 Tutorial

  1. How to Install / Download Codeigniter 4 By Manual, Composer, Git
  2. How to Remove Public and Index.php From URL in Codeigniter 4
  3. Codeigniter 4 Form Validation Example Tutorial
  4. How to add jQuery Validation on Form in Codeigniter 4 Example
  5. Codeigniter 4 Ajax Form Submit Validation Example

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *