Codeigniter 4 Tutorials
- Codeigniter 4
- Application Run
- Application Structure
- Configuration files
- Errors
- Controller
- View
- Model
- How to remove index.php from URL
- Route
- CodeIgniter URLs
- Helper
- Session
- Global Functions and Constants
- Logging Information in CI4
- Error Handling
- Signin / SignUp
- Login / Register
- CRUD
- Crud 1
- Form Validation
- Data Table
- Pagination
- File Upload
- Show Data Using Ajax
- Select2 AJAX Autocomplete Search
- Curl Post
- Rest API
- Weblink
Home » Codeigniter 4 »
How to Upload Multiple Files & Images in Codeigniter 4?
Database Table :-
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;
Create Controller Class :-
File name : UploadMultipleFiles.php
<?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);
}
}
Routes
$routes->get('/', 'UploadMultipleFiles::index');
Create View
File name : index.php
<!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>Upload Multiple Files or Images in Codeigniter 4 - positronx.io</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<style>
.container {
max-width: 500px;
}
</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>
How to upload single file in codeigniter 4?
Create Table
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;
Controller :-
Create Controller for image upload.
File name : index.php
<?php
namespace App\Controllers;
// use App\Models\FormModel;
use CodeIgniter\Controller;
class FileUpload extends Controller
{
public function index()
{
return view('home');
}
function upload() {
helper(['form', 'url']);
$database = \Config\Database::connect();
$db = $database->table('users');
$input = $this->validate([
'file' => [
'uploaded[file]',
'mime_in[file,image/jpg,image/jpeg,image/png]',
'max_size[file,1024]',
]
]);
if (!$input) {
print_r('Choose a valid file');
} else {
$img = $this->request->getFile('file');
$img->move(WRITEPATH . 'uploads');
$data = [
'name' => $img->getName(),
'type' => $img->getClientMimeType()
];
$save = $db->insert($data);
print_r('File has successfully uploaded');
}
}
}
Create Routes
File name : index.php
$routes->get('/', 'FileUpload::index');
View :-
Create Image Upload View
File name : home.php
<!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 File Upload - positronx.io</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<style>
.container {
max-width: 500px;
}
</style>
</head>
<body>
<div class="container mt-5">
<form method="post" action="<?php echo base_url('FileUpload/upload');?>" enctype="multipart/form-data">
<div class="form-group">
<label>Avatar</label>
<input type="file" name="file" class="form-control">
</div>
<div class="form-group">
<button type="submit" class="btn btn-danger">Upload</button>
</div>
</form>
</div>
</body>
</html>
Example : upload file using Codeigniter 4
Controller class
File name : index.php
<?php namespace App\Controllers;
use CodeIgniter\Controller;
use App\Models\ContactModel;
class Contact extends BaseController
{
public function __construct(){
}
public function index()
{
return view('form');
}
public function upload()
{
helper(['form', 'url']);
$db = \Config\Database::connect();
$builder = $db->table('file');
$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 file';
if ($validated) {
$avatar = $this->request->getFile('file');
$avatar->move(WRITEPATH . 'uploads');
$data = [
'name' => $avatar->getClientName(),
'type' => $avatar->getClientMimeType()
];
$save = $builder->insert($data);
$msg = 'File has been uploaded';
}
return redirect()->to( base_url('contact/form') )->with('msg', $msg);
}
}
view
File name : form.php
<!DOCTYPE html>
<html>
<head>
<title>Codeigniter 4 Image upload example</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<br>
<div class="row">
<div class="col-md-4">
<?php if (session('msg')) : ?>
<div class="alert alert-success alert-dismissible">
<?= session('msg') ?>
<button type="button" class="close" data-dismiss="alert"><span>×</span></button>
</div>
<?php endif ?>
<form action="<?php echo base_url('contact/upload');?>" name="ajax_form" id="ajax_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" style="height:35px;">
</div>
<div class="form-group">
<button type="submit" id="send_form" class="btn btn-success">Submit</button>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
Example :-
create Table
File name : index.php
CREATE TABLE files (
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;
controller
File name : Form.php
<?php
namespace App\Controllers;
use CodeIgniter\Controller;
class Form extends Controller
{
public function index()
{
return view('form');
}
public function store()
{
helper(['form', 'url']);
$db = \Config\Database::connect();
$builder = $db->table('file');
$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 file';
if ($validated) {
$avatar = $this->request->getFile('file');
$avatar->move(WRITEPATH . 'uploads');
$data = [
'name' => $avatar->getClientName(),
'type' => $avatar->getClientMimeType()
];
$save = $builder->insert($data);
$msg = 'File has been uploaded';
}
return redirect()->to( base_url('public/index.php/form') )->with('msg', $msg);
}
}
view
File name : view.php
<!DOCTYPE html>
<html>
<head>
<title>Codeigniter 4 Image upload with preview example</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.4.1.js"></script>
</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('form/store');?>" name="ajax_form" id="ajax_form" method="post" accept-charset="utf-8" enctype="multipart/form-data">
<div class="row">
<div class="form-group col-md-6">
<label for="formGroupExampleInput">Name</label>
<input type="file" name="file" class="form-control" id="file" onchange="readURL(this);" accept=".png, .jpg, .jpeg" />
</div>
<div class="form-group col-md-6">
<img id="blah" src="https://www.tutsmake.com/wp-content/uploads/2019/01/no-image-tut.png" class="" width="200" height="150"/>
</div>
<div class="form-group">
<button type="submit" id="send_form" class="btn btn-success">Submit</button>
</div>
</form>
</div>
</div>
</div>
</div>
<script>
function readURL(input, id) {
id = id || '#blah';
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$(id)
.attr('src', e.target.result)
.width(200)
.height(150);
};
reader.readAsDataURL(input.files[0]);
}
}
</script>
</body>
</html>
Example :- Upload Multiple File and Image in ci4
File name : index.php
CREATE TABLE files (
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;
Controller
File name : index.php
<?php
namespace App\Controllers;
use CodeIgniter\Controller;
class Form extends Controller
{
public function multipleImage()
{
return view('multiple-image');
}
public function storeMultipleFile()
{
helper(['form', 'url']);
$db = \Config\Database::connect();
$builder = $db->table('file');
$msg = 'Please select a valid files';
if ($this->request->getFileMultiple('file')) {
foreach($this->request->getFileMultiple('file') as $file)
{
$file->move(WRITEPATH . 'uploads');
$data = [
'name' => $file->getClientName(),
'type' => $file->getClientMimeType()
];
$save = $builder->insert($data);
$msg = 'Files has been uploaded';
}
}
return redirect()->to( base_url('public/index.php/form/multipleImage') )->with('msg', $msg);
}
}
view
File name : index.php
<!DOCTYPE html>
<html>
<head>
<title>Codeigniter 4 Multiple Image upload example</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('public/index.php/form/storeMultipleFile');?>" name="ajax_form" id="ajax_form" method="post" accept-charset="utf-8" enctype="multipart/form-data">
<div class="form-group">
<label for="formGroupExampleInput">Select Files</label>
<input type="file" name="file[]" class="form-control" id="file" multiple>
</div>
<div class="form-group">
<button type="submit" id="send_form" class="btn btn-success">Submit</button>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
File name : index.php
File name : index.php
File name : index.php