Trongate PHP Framework Docs
Introduction
Quick Start
Basic Concepts
Understanding Routing
Intercepting Requests
Module Fundamentals
Database Operations
Templates
Helpers
Form Handling
Form Validation
Working With Files
Image Manipulation
Working With Dates & Times
Language Control
Security
Tips And Best Practices

Image Upload Configuration

Building on the basic upload pattern, the method offers several configuration options that allow you to customize how and where your images are stored, and how they're processed during upload.

All customization happens within the $config array that is passed to the method.

The Configuration Array

The following eight keys allow you to control the behavior of your image uploads:

Key Type Required Default Description
destination string yes N/A The path to the target directory.
upload_to_module bool no false If true, the destination is relative to the module folder.
target_module string no current The module directory to be used for the upload.
make_rand_name bool no false If true, generates a random filename.
max_width int no 450 Maximum width in pixels. Images exceeding this are resized.
max_height int no 450 Maximum height in pixels. Images exceeding this are resized.
thumbnail_dir string no '' Directory for thumbnail generation (empty disables thumbnails).
thumbnail_max_width int no 0 Maximum thumbnail width (0 disables thumbnails).
thumbnail_max_height int no 0 Maximum thumbnail height (0 disables thumbnails).

1. Choosing a Destination

The destination key determines where your uploaded images are stored. The behavior depends on whether you're uploading to the public directory or to a module directory.

Public Directory Uploads

By default (when upload_to_module is false or not set), images are uploaded to a directory within your public folder. This is ideal for publicly accessible images that don't require access control.

PHP
$config['destination'] = 'gallery';

// Result: gallery/image.jpg
$file_info = $this->image->upload($config);

Important: Before uploading to the public directory, ensure the target directory exists and has the correct permissions (typically 755).

Module-Based Uploads

Setting upload_to_module to true keeps your images contained within your module directory.

PHP
$config['destination'] = 'avatars';
$config['upload_to_module'] = true;

// Result: modules/your_module/avatars/image.jpg
$file_info = $this->image->upload($config);

External Module Uploads

If you are in one module (e.g., 'admin') but want to save images into another module (e.g., 'products'), you can use the target_module key. This is useful for centralized admin interfaces that manage content across multiple modules. The target_module key is also useful for scenarios where custom routing is being applied.

PHP
$config['destination'] = 'product_images';
$config['upload_to_module'] = true;
$config['target_module'] = 'products';

// Result: modules/products/product_images/image.jpg
$file_info = $this->image->upload($config);

2. Automatic Resizing

One of the Image module's most powerful features is automatic resizing during upload. If an uploaded image exceeds your specified maximum dimensions, it's automatically resized while preserving the aspect ratio.

Setting Maximum Dimensions

PHP
$config = [
    'destination' => 'uploads',
    'upload_to_module' => true,
    'max_width' => 1200,
    'max_height' => 800
];

$file_info = $this->image->upload($config);

How Automatic Resizing Works

The Image module intelligently resizes images based on which dimension exceeds the limit by the greatest factor:

  • If the image is 2000x1000 with limits of 1200x800:
    • Width factor: 2000 ÷ 1200 = 1.67
    • Height factor: 1000 ÷ 800 = 1.25
    • Width exceeds more, so resize to width → Result: 1200x600
  • If the image is 1000x2000 with limits of 1200x800:
    • Width factor: 1000 ÷ 1200 = 0.83 (within limit)
    • Height factor: 2000 ÷ 800 = 2.5
    • Height exceeds more, so resize to height → Result: 400x800

Pro Tip: Set max_width and max_height to 0 to disable automatic resizing entirely. This is useful when you need to preserve original image dimensions.

Memory Management: The Image module automatically calculates whether your server has enough memory to process an image before attempting resizing. If an image would require more memory than available, the upload is rejected with a clear error message. This prevents server crashes from processing extremely large images.

3. Thumbnail Generation

The Image module can automatically generate thumbnails during upload. This happens in addition to the main image upload and uses the same intelligent resizing logic.

Basic Thumbnail Configuration

PHP
$config = [
    'destination' => 'uploads',
    'upload_to_module' => true,
    'max_width' => 1200,
    'max_height' => 800,
    'thumbnail_dir' => 'uploads/thumbs',
    'thumbnail_max_width' => 200,
    'thumbnail_max_height' => 200
];

$file_info = $this->image->upload($config);

/*
Result:
- Main image: modules/your_module/uploads/image.jpg (max 1200x800)
- Thumbnail: modules/your_module/uploads/thumbs/image.jpg (max 200x200)
*/

Thumbnail Requirements

For thumbnails to be generated, all three thumbnail parameters must be set:

  • thumbnail_dir must be a non-empty string
  • thumbnail_max_width must be greater than 0
  • thumbnail_max_height must be greater than 0

If any of these conditions are not met, thumbnail generation is skipped.

Note: The thumbnail_dir path follows the same upload_to_module rules as destination. If upload_to_module is true, the thumbnail directory is relative to the target module. The thumbnail directory is created automatically if it doesn't exist.

4. Handling Filenames

Trongate gives you two ways to handle the naming of uploaded images.

Original Filenames

By default, the original filename is preserved (after sanitization). If an image with the same name already exists in the destination folder, Trongate will automatically append a numeric suffix (e.g., photo_2.jpg) to prevent overwriting.

PHP
$config['destination'] = 'uploads';
$config['upload_to_module'] = true;
$config['make_rand_name'] = false;  // Default behavior

$file_info = $this->image->upload($config);

// If 'sunset.jpg' already exists:
// First upload: sunset.jpg
// Second upload: sunset_2.jpg
// Third upload: sunset_3.jpg

Random Filenames

For improved security and to prevent users from guessing image URLs, you can generate a random filename. The original file extension is always preserved.

PHP
$config['destination'] = 'avatars';
$config['upload_to_module'] = true;
$config['make_rand_name'] = true;

// Original: profile-photo.jpg
// Result: img_6756d8e9a2b4f3.21.jpg
$file_info = $this->image->upload($config);

The Image module uses Trongate's built-in function to ensure all uploaded images have safe, URL-friendly names. This function automatically handles international characters, removes special characters, replaces spaces with hyphens, and prevents security issues like null byte attacks - all without any configuration required.

5. Processing the Return Data

Once has executed successfully, it returns an array containing metadata about the image. This is useful for displaying information to the user or preparing data for a database entry.

PHP
$file_info = $this->image->upload($config);

/*
$file_info contains:
[
    'file_name' => 'beach_2.jpg',
    'file_path' => 'modules/gallery/uploads/beach_2.jpg',
    'file_type' => 'image/jpeg',
    'file_size' => 245760,
    'thumbnail_path' => 'modules/gallery/uploads/thumbs/beach_2.jpg' // Only if thumbnail was generated
]
*/

Note: The file_size is returned in bytes. The thumbnail_path key is only present if thumbnail generation was requested and successful.

Real-World Example: User Avatar Upload with Database Integration

Let's combine what we've learned with a practical scenario: allowing users to upload avatar images with automatic resizing and thumbnail generation. This example demonstrates how to store image references in your database for later retrieval.

Why Database Integration Matters

When you use random filenames for security, you need a way to retrieve those images later. Storing image metadata in your database allows you to:

  • Associate images with users: Track who uploaded what and when
  • Retrieve images reliably: Find images using database queries instead of guessing filenames
  • Display image information: Show upload dates, file sizes, and dimensions to users
  • Manage images programmatically: Build delete, update, and replacement features

The Complete Implementation

PHP
public function submit_avatar(): void {
    $this->validation->set_rules(
        'avatar', 
        'Avatar', 
        'required|max_size[5000]|max_width[4000]|max_height[4000]'
    );
    
    if ($this->validation->run() === true) {
        $user_id = segment(3);
        
        // Configure upload with automatic processing
        $config = [
            'destination' => 'avatars',
            'upload_to_module' => true,
            'make_rand_name' => true,
            'max_width' => 800,
            'max_height' => 800,
            'thumbnail_dir' => 'avatars/thumbs',
            'thumbnail_max_width' => 150,
            'thumbnail_max_height' => 150
        ];
        
        $file_info = $this->image->upload($config);
        
        // Store image reference in database
        $data = [
            'avatar_filename' => $file_info['file_name'],
            'avatar_path' => $file_info['file_path'],
            'thumbnail_path' => $file_info['thumbnail_path'],
            'file_size' => $file_info['file_size'],
            'upload_date' => date('Y-m-d H:i:s')
        ];
        
        $this->model->update($user_id, $data, 'users');
        
        set_flashdata('Avatar uploaded successfully!');
        redirect('users/profile/' . $user_id);
    } else {
        redirect('users/avatar_upload/' . $user_id);
    }
}

Understanding the Pattern

This example follows the same clean pattern from the basic uploader:

  1. Validate first: Check file type, size, and dimensions before uploading
  2. Configure the upload: Set dimensions for both main image and thumbnail
  3. Upload the image: The Image module handles all processing automatically
  4. Store the references: Save both the main image path and thumbnail path to your database
  5. Redirect on success: Use the POST-Redirect-GET pattern

Configuration Combinations

Here are some common configuration patterns for different use cases:

Product Gallery (High Quality, Multiple Sizes)

PHP
$config = [
    'destination' => 'products',
    'upload_to_module' => true,
    'make_rand_name' => true,
    'max_width' => 2000,
    'max_height' => 2000,
    'thumbnail_dir' => 'products/thumbs',
    'thumbnail_max_width' => 300,
    'thumbnail_max_height' => 300
];

User Profile Pictures (Square Thumbnails)

PHP
$config = [
    'destination' => 'avatars',
    'upload_to_module' => true,
    'make_rand_name' => true,
    'max_width' => 800,
    'max_height' => 800,
    'thumbnail_dir' => 'avatars/thumbs',
    'thumbnail_max_width' => 150,
    'thumbnail_max_height' => 150
];

Blog Post Images (No Thumbnails)

PHP
$config = [
    'destination' => 'blog_images',
    'upload_to_module' => true,
    'make_rand_name' => false,
    'max_width' => 1200,
    'max_height' => 0  // No height restriction
];
// Note: Omitting thumbnail settings disables thumbnail generation

Original Quality Preservation

PHP
$config = [
    'destination' => 'originals',
    'upload_to_module' => true,
    'make_rand_name' => true,
    'max_width' => 0,  // No resizing
    'max_height' => 0  // No resizing
];
// Note: Set both to 0 to preserve original dimensions

Key Takeaways

Remember these essentials:

  • The destination key is required - all other keys have sensible defaults
  • Automatic resizing preserves aspect ratios and only triggers when images exceed limits
  • Thumbnail generation requires all three thumbnail parameters to be set
  • Use make_rand_name for security when storing user-uploaded images
  • The Image module creates directories automatically if they don't exist
  • Store the complete $file_info array in your database for easy retrieval
  • Set max dimensions to 0 to disable automatic resizing
  • The thumbnail_path key is only present when thumbnails are generated

We're continually improving the Trongate documentation. If anything is incorrect, unclear, incomplete, or could be better, we'd genuinely appreciate your input.

Share your thoughts in the Documentation Feedback.

Leave Feedback About This Page