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 uploadedis_image[photo]mime_in[photo,image/jpeg,image/png,image/webp]ext_in[photo,jpg,jpeg,png,webp]max_size[photo,2048]— in KBmax_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);—FCPATHis thepublicfolder
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
<?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".