Upload File with Validation in CodeIgniter 4
In CodeIgniter 4, there is CodeIgniter\Validation\FileRules
that can be used out of the box from validate()
from controllers that we can using it on upload process.
For example, we have an upload form page with flow as follow:
- Display form at /form page with “avatar” file field
- Process form at /form/process with validations:
- is uploaded
- is mime in image/jpg,image/jpeg,image/gif,image/png
- the max size is less or equal than 4MB
- On valid upload, we move uploaded file to writable/uploads directory.
Before we start, please ensure that you’re using latest CodeIgniter4
develop branch by clone it:
$ git clone https://github.com/bcit-ci/CodeIgniter4.git
If you already have it, ensure to pull latest develop branch via command:
$ cd CodeIgniter4 $ git checkout develop $ git remote add upstream https://github.com/bcit-ci/CodeIgniter4.git $ git pull upstream develop
Most of the time, the updated code in the CodeIgniter4
repository will be core framework (system) and its tests
, so, if we need to be always up to date framework, we can create new branch based on develop
branch, for example:
$ git checkout -b tutorial-upload
Then, we can regularly rebase against develop :
$ git checkout develop && git pull upstream develop $ git checkout tutorial-upload && git rebase develop
Enough with introduction, let’s start with code!
1. Display Form
<?php // application/Views/form.php $validationErrors = $this->config->plugins['validation_errors']; helper('form'); echo form_open( 'form/process', [ 'enctype' => 'multipart/form-data' ] ); echo form_input('avatar', '', '', 'file'); echo $validationErrors(['field' => 'avatar']); echo form_submit('Send', 'Send'); echo form_close();
Above, we display form with form helpers, and display validation errors by get it in validation_errors
key in plugins.
To make it a form page, we can create a Form controller as follow:
<?php // application/Controllers/Form.php namespace App\Controllers; use CodeIgniter\Controller; class Form extends Controller { public function index() { return view('form'); } }
To see the page, let’s fire a command:
$ php spark serve
The form page is now displayed at http://localhost:8080/form
or http://localhost:8080/form/index
like below:
2. Upload validation
We are going to use “form/process” page for file upload validation, so, we can create an process()
function at the Form controller:
class Form extends Controller { // ... public function process() { // verify if request method is POST if ($this->request->getMethod() !== 'post') { return redirect('index'); } // validation $validated = $this->validate([ 'avatar' => [ 'uploaded[avatar]', 'mime_in[avatar,image/jpg,image/jpeg,image/gif,image/png]', 'max_size[avatar,4096]', ], ]); if ($validated) { // Business! } return redirect('index')->withInput(); } }
On above process()
function, the validate()
call supply the rules of avatar field needed, which are uploaded, mime_in, and max_size which we can found as functions at CodeIgniter\Validation\FileRules
. When it is valid, it will returns true. We redirect back to /form/index
with bring validation errors that saved in session flash with key _ci_validation_errors
to be allowed to be displayed once in the next request like below:
3. Move uploaded file to writable/uploads
directory
We have a WRITEPATH
constant that refers to writable directory, and we can use its “$request->getFile(‘avatar’)->move()” to it, so when we have validated, we can do:
if ($validated) { $avatar = $this->request->getFile('avatar'); $avatar->move(WRITEPATH . 'uploads'); }
That’s it! The complete Form
controller class can be as follow:
<?php // application/Controllers/Form.php namespace App\Controllers; use CodeIgniter\Controller; class Form extends Controller { public function index() { return view('form'); } public function process() { if ($this->request->getMethod() !== 'post') { return redirect('index'); } $validated = $this->validate([ 'avatar' => [ 'uploaded[avatar]', 'mime_in[avatar,image/jpg,image/jpeg,image/gif,image/png]', 'max_size[avatar,4096]', ], ]); if ($validated) { $avatar = $this->request->getFile('avatar'); $avatar->move(WRITEPATH . 'uploads'); } return redirect('index')->withInput(); } }
how to show file that save on writeable/upload if the root is public?
you may can create an action that read the file, and read it there, eg :
Some way to display the file through the URL..
then how to view image
<img src="”>
see comment see comment https://samsonasik.wordpress.com/2018/09/05/upload-file-with-validation-in-codeigniter-4/#comment-34448
how to view the uploaded images
see comment https://samsonasik.wordpress.com/2018/09/05/upload-file-with-validation-in-codeigniter-4/#comment-34448
that is not working.could you please explain how to show uploaded images in img tag
please do effort.
how to make validation in model? like …
protected $validationRules = [
‘jurusan’ => ‘required|string’,
‘kapasitas’ => ‘required|integer’,
‘terisi’ => ‘integer|less_than_equal_to[kapasitas]’
];
protected $validationMessages = [
‘jurusan’ => [
‘required’ => ‘Jurusan Wajib di isi’,
‘string’ => ‘Isi sesuai aturan’
],
‘kapasitas’ => [
‘required’ => ‘Kapasitas Wajib di isi’,
‘integer’ => ‘Kapasitas hanya dapat di isi dengan angka’
],
‘terisi’ => [
‘integer’ => ‘Terisi hanya dapat di isi dengan angka’
]
];
How to apply in Controller ?
validation rules in model will work out of the box specifically if you use `model->save()`.
samsonasik, thanks for nice tutorial and thanks for your contributions on codeigniter4.. it will help many people’s to understand new concepts of codeigniter4.
can you please please prepare more tutorials on codeigniter4 and modules development? i will be very helpful for other people’s to understand it in depth.
Thanks, you can make a donation to support me https://samsonasik.wordpress.com/donate/