Code your dreams into reality.
Every line of code is a step towards a better future.
Embrace the bugs, they make you a better debugger.

Upload Multiple Images in CodeIgniter 4

Last Updated on July 17, 2024 by

To create multiple image upload feature in Codeigniter 4 application, you need to create a form and connect it to the controller method through route.

Let’s start to create multiple image upload feature in codeIgniter application:

Step 1 – Set up CodeIgniter

To download CodeIgniter 4 from the official website, Link: https://codeigniter.com/user_guide/installation/index.html.

Extract downloaded zip file in xampp/htdocs directory. and edit app/Config/App.php file, and set up base url in it:

public $baseURL = 'http://localhost/your-project/public';

Step 2 – Create Table in Database

Run the following sql query to create table in to your selected database:

CREATE TABLE users (
    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',
    PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='users table' AUTO_INCREMENT=1;

Step 3 – Configure Database

Edit application/config/database.php file, and set up your database details in it:

public $default = [
        'DSN'      => '',
        'hostname' => 'localhost',
        'username' => 'root',
        'password' => 'root',
        '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 4 – Create Controller

Go to app/Controllers/ directory and create a new controller file named UploadMultipleFiles.php, and implement methods in it to handle multiple image upload:

<?php 
namespace App\Controllers;
use CodeIgniter\Controller;

class UploadMultipleFiles extends Controller
{

    public function index() {
        return view('home');
    }

    function uploadFiles() {
        helper(['form', 'url']);
 
        $database = \Config\Database::connect();
        $db = $database->table('users');
 
        $msg = 'Please select a valid files';
  
        if ($this->request->getFileMultiple('images')) {
 
             foreach($this->request->getFileMultiple('images') as $file)
             {   
 
                $file->move(WRITEPATH . 'uploads');
 
              $data = [
                'name' =>  $file->getClientName(),
                'type'  => $file->getClientMimeType()
              ];
 
              $save = $db->insert($data);
              $msg = 'Files have been successfully uploaded';
             }
        }
 
        return redirect()->to( base_url('/') )->with('msg', $msg);        
    }

}

Step 5 – Create Image Upload View and Form

Go to app/Views/ directory and create home.php file, and create a multiple image upload form in it:

<!doctype html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <title>CodeIgniter 4 Upload Multiple Images Example - itcodstuff.com</title>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
  <style>
    .container {
      max-width: 600px;
    }
  </style>
</head>

<body>
  <div class="container mt-5">
    <?php if (session('msg')) : ?>
        <div class="alert alert-success mt-3">
            <?= session('msg') ?>
        </div>
    <?php endif ?>    

    <form method="post" action="<?php echo base_url('UploadMultipleFiles/uploadFiles');?>" 
    enctype="multipart/form-data">
      <div class="form-group mt-3">
        <input type="file" name='images[]' multiple="" class="form-control">
      </div>

      <div class="form-group">
        <button type="submit" class="btn btn-danger">Upload</button>
      </div>
    </form>

  </div>
</body>

</html>

Step 6 – Define Route

Edit app/Config/Routes.php file, and define routes in it to handle multiple image upload requests on controller:

/*
 * --------------------------------------------------------------------
 * Route Definitions
 * --------------------------------------------------------------------
*/

$routes->get('/', 'UploadMultipleFiles::index');
$routes->match(['get', 'post'], 'UploadMultipleFiles/uploadFiles', 'UploadMultipleFiles::uploadFiles');

Step 7 – Test Application

Run the following command to start application server:

php spark serve

Test this application on browser by typing URL http://localhost:8080.

Leave a Comment