upload()
public function upload(array $data): array
Description
Handles the complete image upload process including validation, file storage, automatic resizing, and thumbnail generation. This method manages the entire upload workflow from receiving the uploaded file through to saving processed versions with proper security validation.
Validate Before Upload: Always use Trongate's validation module to check file requirements before calling upload(). The validation module verifies file type, size, and dimensions. The upload() method handles physical file transfer and processing after validation passes.
Parameters
| Parameter | Type | Description | Required |
|---|---|---|---|
| $data | array | Associative array containing upload configuration options. | Yes |
Configuration Array Keys
The $data array controls all aspects of the upload process:
| Key | Type | Required | Default | Description |
|---|---|---|---|---|
| destination | string | Yes | N/A | Target directory path. Behaviour depends on upload_to_module setting. |
| upload_to_module | bool | No | false | If true, uploads to module directory. If false, uploads to public directory. |
| target_module | string | No | segment(1) | Specific module name when upload_to_module is true. |
| make_rand_name | bool | No | false | Generate random filename whilst preserving extension. |
| max_width | int | No | 450 | Maximum width in pixels. Images exceeding this are resized. Set to 0 to disable. |
| max_height | int | No | 450 | Maximum height in pixels. Images exceeding this are resized. Set to 0 to disable. |
| thumbnail_dir | string | No | '' | Directory for thumbnail generation. Empty string disables thumbnails. |
| thumbnail_max_width | int | No | 0 | Maximum thumbnail width. 0 disables thumbnail generation. |
| thumbnail_max_height | int | No | 0 | Maximum thumbnail height. 0 disables thumbnail generation. |
Return Value
Returns an associative array containing metadata about the successfully uploaded file:
| Key | Type | Description |
|---|---|---|
| file_name | string | The final filename as stored on disk (may differ from original). |
| file_path | string | The complete filesystem path to the uploaded file. |
| file_type | string | The detected MIME type (e.g., "image/jpeg", "image/png"). |
| file_size | int | File size in bytes. |
| thumbnail_path | string | Complete path to generated thumbnail (only present if thumbnail created). |
Automatic Security Validation: The upload() method performs four layers of security checks automatically: (1) MIME type verification using finfo and getimagesize(), (2) File signature validation to prevent extension spoofing, (3) Script injection prevention scanning first 256 bytes for dangerous content, (4) Memory limit enforcement to prevent server overload. These checks run automatically with no configuration required.
Example #1
The code sample below demonstrates the most basic image upload.
// Validate the upload
$this->validation->set_rules('userfile', 'Image', 'required|allowed_types[jpg,png]|max_size[5000]');
if ($this->validation->run() === true) {
// Configure upload
$config['destination'] = 'uploads';
$config['upload_to_module'] = true;
// Upload the image
$file_info = $this->image->upload($config);
set_flashdata('Image uploaded: ' . $file_info['file_name']);
redirect('gallery/success');
}The Standard Upload Pattern: Always validate first with the validation module, then call upload() only if validation passes. The method automatically handles file storage, security checks, and returns metadata for database storage or display.
Example #2: Complete Upload Form
The example above shows a complete image upload form that works with the upload() method.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Upload Image</title>
</head>
<body>
<h1>Upload Image</h1>
<?= validation_errors() ?>
<div class="info">
<p><strong>Allowed file types:</strong> JPEG, PNG, GIF, WEBP</p>
<p><strong>Maximum file size:</strong> 5 MB</p>
<p><strong>Maximum dimensions:</strong> 3000 x 3000 pixels</p>
<p><strong>Note:</strong> Images larger than 800x800px will be automatically resized. A 150x150px thumbnail will be generated.</p>
</div>
<?php
echo form_open_upload('gallery/submit_upload');
echo form_label('Select Image:', ['for' => 'userfile']);
$select_attr = [
'id' => 'userfile',
'accept' => 'image/jpeg,image/png,image/gif,image/webp'
];
echo form_file_select('userfile', $select_attr);
echo form_submit('submit', 'Upload Image');
echo form_close();
?>
</body>
</html>Form Requirements: Use form_open_upload() instead of form_open() - this automatically adds the enctype="multipart/form-data" attribute required for file uploads. The file input name (in this example, 'userfile') must match the name used in your validation rules.
Example #3
The example above shows how to upload with automatic resizing and thumbnail generation.
public function submit_product_image(): void {
$product_id = segment(3, 'int');
// Validate image upload
$this->validation->set_rules('userfile', 'Product Image', 'required|allowed_types[jpg,png]|max_size[5000]|max_width[4000]|max_height[4000]');
if ($this->validation->run() === true) {
// Configure upload with automatic processing
$config = [
'destination' => 'products/images',
'upload_to_module' => true,
'target_module' => 'products',
'make_rand_name' => true,
'max_width' => 1200,
'max_height' => 1200,
'thumbnail_dir' => 'products/images/thumbs',
'thumbnail_max_width' => 300,
'thumbnail_max_height' => 300
];
// Upload with automatic resizing and thumbnail generation
$file_info = $this->image->upload($config);
// Store image references in database
$data = [
'product_id' => $product_id,
'filename' => $file_info['file_name'],
'file_path' => $file_info['file_path'],
'thumbnail_path' => $file_info['thumbnail_path'],
'file_size' => $file_info['file_size'],
'uploaded_at' => date('Y-m-d H:i:s')
];
$this->model->insert($data, 'product_images');
set_flashdata('Product image uploaded successfully');
redirect('products/view/' . $product_id);
} else {
$this->image_upload_form($product_id);
}
}Automatic Processing: When you configure max_width/max_height and thumbnail parameters, the upload() method automatically: resizes the main image if it exceeds dimensions (preserving aspect ratio), generates a thumbnail with specified dimensions, creates directories if they don't exist, and returns paths to both versions for database storage.
Example #4
The example above demonstrates uploading user avatars with random filenames for security.
public function submit_avatar(): void {
$user_id = segment(3, 'int');
// Verify user exists
$user = $this->db->get_where($user_id, 'users');
if ($user === false) {
redirect('users/not_found');
}
// Validate avatar upload
$this->validation->set_rules('userfile', 'Avatar', 'required|allowed_types[jpg,png,gif]|max_size[3000]|max_width[2000]|max_height[2000]');
if ($this->validation->run() === true) {
// Delete old avatar if it exists
if (!empty($user->avatar_filename)) {
$old_avatar = 'modules/users/avatars/' . $user->avatar_filename;
if ($this->file->exists($old_avatar)) {
$this->file->delete($old_avatar);
}
// Delete old thumbnail
$old_thumb = 'modules/users/avatars/thumbs/' . $user->avatar_filename;
if ($this->file->exists($old_thumb)) {
$this->file->delete($old_thumb);
}
}
// Configure upload with random filename
$config = [
'destination' => 'avatars',
'upload_to_module' => true,
'target_module' => 'users',
'make_rand_name' => true,
'max_width' => 400,
'max_height' => 400,
'thumbnail_dir' => 'avatars/thumbs',
'thumbnail_max_width' => 150,
'thumbnail_max_height' => 150
];
$file_info = $this->image->upload($config);
// Update user record
$update_data = [
'avatar_filename' => $file_info['file_name'],
'avatar_path' => $file_info['file_path'],
'thumbnail_path' => $file_info['thumbnail_path'],
'avatar_updated_at' => date('Y-m-d H:i:s')
];
$this->model->update($user_id, $update_data, 'users');
set_flashdata('Avatar updated successfully');
redirect('users/profile/' . $user_id);
} else {
$this->avatar_upload_form($user_id);
}
}Random Filenames for Security: Setting make_rand_name to true prevents users from guessing file URLs. The method generates unique filenames like "img_6756d8e9a2b4f3.21.jpg" whilst preserving the original extension. Always store the returned filename in your database for later retrieval.
Example #5
The example above shows uploading to preserve original quality without resizing.
public function submit_portfolio_image(): void {
$portfolio_id = segment(3, 'int');
// Get portfolio record
$portfolio = $this->db->get_where($portfolio_id, 'portfolios');
if ($portfolio === false) {
redirect('portfolios/not_found');
}
// Validate high-resolution image
$this->validation->set_rules('userfile', 'Portfolio Image', 'required|allowed_types[jpg,png]|max_size[20000]');
if ($this->validation->run() === true) {
// Configure upload - preserve original dimensions
$config = [
'destination' => 'portfolios/originals',
'upload_to_module' => true,
'make_rand_name' => true,
'max_width' => 0, // No resizing
'max_height' => 0, // No resizing
'thumbnail_dir' => 'portfolios/previews',
'thumbnail_max_width' => 400,
'thumbnail_max_height' => 400
];
$file_info = $this->image->upload($config);
// Load original to get actual dimensions
$this->image->load($file_info['file_path']);
$original_width = $this->image->get_width();
$original_height = $this->image->get_height();
$this->image->destroy();
// Create web-optimised version
$this->image->load($file_info['file_path']);
$this->image->resize_to_width(1920);
$web_dir = 'modules/portfolios/portfolios/web';
if (!$this->file->exists($web_dir)) {
$this->file->create_directory($web_dir, 0755);
}
$web_path = $web_dir . '/' . $file_info['file_name'];
$this->image->save($web_path, 85);
$this->image->destroy();
// Store all versions in database
$data = [
'portfolio_id' => $portfolio_id,
'original_filename' => $file_info['file_name'],
'original_path' => $file_info['file_path'],
'original_width' => $original_width,
'original_height' => $original_height,
'web_path' => $web_path,
'thumbnail_path' => $file_info['thumbnail_path'],
'file_size' => $file_info['file_size'],
'uploaded_at' => date('Y-m-d H:i:s')
];
$this->model->insert($data, 'portfolio_images');
set_flashdata('Portfolio image uploaded successfully');
redirect('portfolios/view/' . $portfolio_id);
} else {
$this->image_upload_form($portfolio_id);
}
}Preserving Original Quality: Set both max_width and max_height to 0 to disable automatic resizing entirely. This preserves original dimensions and quality, useful for archival purposes, print-ready images, or when you want to create custom processed versions later. You can still generate thumbnails whilst preserving the original.