Validate and move uploaded files in CI4 with type, size, and extension rules for security.
File Upload
public function upload() {
$file = $this->request->getFile("avatar");
// Validate
if (!$file->isValid() || $file->hasMoved()) {
throw new RuntimeException($file->getErrorString());
}
// Validate size and type
$rules = [
"avatar" => [
"label" => "Avatar",
"rules" => "uploaded[avatar]|is_image[avatar]|max_size[avatar,2048]|ext_in[avatar,jpg,png,webp]",
],
];
if (!$this->validate($rules)) {
return redirect()->back()->with("errors", $this->validator->getErrors());
}
// Move to uploads folder
$newName = $file->getRandomName();
$file->move(WRITEPATH . "uploads", $newName);
// Save path to database
model(UserModel::class)->update(auth()->id(), ["avatar" => $newName]);
return redirect()->back()->with("success", "Uploaded: " . $newName);
}