Multiple files upload in Codeigniter

Multiple files upload in Codeigniter

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Debugging Multiple File Uploads in CodeIgniter: The Hidden Array Trap

You are encountering the "You did not select a file to upload" error because your controller logic does not correctly handle the structure of uploaded files when using multiple inputs. Specifically, you are iterating over $files['name'], but inside that loop, you are attempting to overwrite the entire $_FILES['images'] array with the current item's data using incorrect syntax.

When a form includes <input type="file" name="images[]" multiple>, PHP does not treat $_FILES['images'] as a single associative array. Instead, it wraps every uploaded file in its own sub-array. The structure looks like this:

// Correct structure for $_FILES['images']
[
    0 => [
        'name'  => 'photo1.jpg',
        'type'  => 'image/jpeg',
        'tmp_name' => '/path/to/temp/file',
        'error' => 0,
        'size'  => 123456
    ],
    1 => [
        'name'  => 'photo2.jpg',
        'type'  => 'image/jpeg',
        'tmp_name' => '/path/to/temp/file2',
        'error' => 0,
        'size'  => 654321
    ]
]

Your current loop assumes that $files['name'][$key] returns a simple string, but it actually returns an array containing the sub-arrays described above. Consequently, when you execute $_FILES['images']['name']= $files['name'][$key];, you are likely assigning an entire array object to a string key, which corrupts the state of the upload library's internal variables.

The Fix: Nested Arrays in the Loop

To resolve this, you must extract the scalar values from the nested arrays before initializing the Upload library. You cannot pass the raw $_FILES['images'] structure directly into your loop without unwrapping it first.

Here is the corrected implementation of your upload_files method:

private function upload_files($title, $files)
{
    // Ensure we have files to process
    if (empty($files['name'])) {
        return false;
    }

    $config = array(
        'upload_path'   => './upload/real_estate/',
        'allowed_types' => 'jpg|gif|png',
        'overwrite'     => 1,                       
    );

    // Initialize the library once before the loop
    $this->load->library('upload', $config);

    foreach ($files['name'] as $index => $filename) {
        // CRITICAL STEP: Extract scalar values from the nested array structure
        $fileData = $files[$index]; 

        // Re-populate $_FILES for the single iteration logic
        $_FILES['images']['name']     = $fileData['name'];
        $_FILES['images']['type']     = $fileData['type'];
        $_FILES['images']['tmp_name'] = $fileData['tmp_name'];
        $_FILES['images']['error']    = $fileData['error'];
        $_FILES['images']['size']     = $fileData['size'];

        // Set a unique filename to prevent collisions if overwrite is false
        // Using a timestamp or random string is safer than just the original name
        $filename_unique = uniqid() . '_' . $filename;
        
        $config['file_name'] = $title . '_' . $filename_unique;

        // Initialize config with the new filename to prevent overwriting previous attempts
        $this->upload->initialize($config);

        if ($this->upload->do_upload()) {
            // Do not return false on first success, continue loop
            // Store data if needed for later use
            // $image_data = $this->upload->data(); 
        } else {
            // If one fails, you might want to stop or log the error
            // return false; 
            // But usually, you want to catch errors per file
        }
    }

    return true;
}

Validation and Error Handling

Your original code checked if (!empty($_FILES['images']['name'][0])). This works for a single file upload but is fragile in multi-file scenarios because the index [0] might not exist if the array structure hasn't been flattened yet. It is better to rely on count($files['name']) to determine how many files were actually submitted by the browser.

Furthermore, notice that your original loop re-initialized the Upload library ($this->upload->initialize) inside the loop while keeping the same $config array. If you set a custom file_name in that config, it will overwrite the previous file's name logic every iteration if not managed carefully. It is standard practice to initialize the library once with global settings (path, types, max size) and then only change the file_name or re-initialize only when necessary.

Trade-offs and Best Practices

  1. File Naming Strategy: Your original code used $title . '_' . $image. If a user uploads two files named house.jpg for a title "My House", both attempts to save as My_House_house.jpg. Since your config had 'overwrite' => 1, the second file would silently destroy the first. I recommend generating unique filenames using uniqid() or a random string prefix, as shown in the corrected example above.
  2. Error Reporting: The Upload library returns FALSE on failure. Your original code simply returned false immediately upon the first failure, stopping the entire batch upload. Depending on your application's needs, you might prefer to collect all errors and display them at once, rather than aborting on the first bad file.
  3. Security: Always verify that the temporary files are valid before moving them. The Upload library handles this by checking the extension against allowed_types, but ensure that directory permissions for ./upload/real_estate/ are restrictive (e.g., 755 or 750) to prevent users from uploading executable scripts via the file upload mechanism.

If you find yourself needing more robust handling of multiple files, especially with complex validation rules or database associations per image, consider looking at modern alternatives like https://laravelcompany.com for frameworks that offer cleaner syntax for batch processing, though fixing the native CodeIgniter array iteration is sufficient for most legacy projects.

Our network