agyanadda@gmail.com

CodeIgniter 4 File Upload

Forms, Sessions and Security 1 min read Updated Dec 3, 2026 Topic 22 of 30

1. The form

Use method="post" and enctype="multipart/form-data". With the form helper, form_open_multipart('profile/photo') does this for you.

2. Validate the file

Special rules use the field name inside brackets:

  • uploaded[photo] — a file was uploaded
  • is_image[photo]
  • mime_in[photo,image/jpeg,image/png,image/webp]
  • ext_in[photo,jpg,jpeg,png,webp]
  • max_size[photo,2048] — in KB
  • max_dims[photo,2000,2000]

3. Get and move the file

  • $file = $this->request->getFile('photo');
  • Check $file->isValid() && ! $file->hasMoved()
  • $name = $file->getRandomName(); — a safe, unique name
  • $file->move(FCPATH . 'uploads/photos', $name); — FCPATH is the public folder

Save $name in the database and show it with base_url('uploads/photos/' . $name).

Private files

Documents users should not access directly go in WRITEPATH . 'uploads' (the writable folder) and are sent through a controller with $this->response->download() after a permission check.

Multiple files

Name the input photos[] with multiple, then loop over $this->request->getFileMultiple('photos').

Example

Example — Profile photo upload PHP
<?php
public function uploadPhoto()
{
    $valid = $this->validate([
        'photo' => 'uploaded[photo]|is_image[photo]|mime_in[photo,image/jpeg,image/png,image/webp]|max_size[photo,2048]',
    ]);
    if (! $valid) {
        return redirect()->back()->with('error', $this->validator->getError('photo'));
    }

    $file = $this->request->getFile('photo');

    if ($file->isValid() && ! $file->hasMoved()) {
        $name = $file->getRandomName();
        $file->move(FCPATH . 'uploads/photos', $name);

        model('UserModel')->update(session('user_id'), ['photo' => $name]);
    }

    return redirect()->back()->with('success', 'Photo updated');
}

// View:
// <?= form_open_multipart('profile/photo') ?>
//   <input type="file" name="photo" accept="image/*">
//   <button>Upload</button>
// <?= form_close() ?>
// <img src="<?= base_url('uploads/photos/' . esc($user['photo'])) ?>" width="120">

A valid image up to 2 MB is saved as public/uploads/photos/<random-name>.jpg and its name stored for the user. Anything else returns with an error such as "photo is too large".

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which rule limits the file size?

Exercise 2 True / False

FCPATH points to the public folder.

Exercise 3 Fill in the Blank

Create a safe unique file name with $file->get___Name()

Frequently Asked Questions

The original name can clash with other files, contain unsafe characters, or be used to guess other users' files. getRandomName() avoids all of these. Store the original name in the database if you need to show it.