Codeigniter Rename file on upload

Codeigniter Rename file on upload

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

Stefan Bogdanescu

Founder & Senior Architect

Renaming Uploaded Files in CodeIgniter: Adding Time Prefixes to Filenames

When handling file uploads, one of the most common requirements is ensuring unique filenames to prevent overwrites and improve organization. A frequent pattern involves prepending a timestamp or random string to the original filename provided by the user. In CodeIgniter, this logic lives within your controller's upload handler, but it requires specific configuration to work correctly without breaking the library's internal expectations.

The standard approach uses the upload library's configuration array. You can modify the file name before the file is actually moved to the destination directory by setting the file_name property in the $config array passed to the library initialization. However, you must be careful about how you construct this string. The upload library expects the file_name configuration value to be a complete path relative to your upload folder (e.g., images/new_filename.jpg).

If you simply concatenate the timestamp and original name into the file_name config without ensuring the extension remains intact or handling the logic correctly, the library might reject the file or overwrite an existing one. For instance, if your configuration looks like this:

$config['file_name'] = date('YmdHis') . '_' . $this->input->post('name'); 

You risk losing the original file extension if the user input doesn't include it, or you might inadvertently skip the library's validation steps that rely on the extension matching the allowed_types setting. It is safer to let the library handle the validation first and then intervene only to rename the file after a successful upload, or to construct the full target filename explicitly in the config while ensuring the extension is preserved.

To implement a time prefix, you have two primary strategies depending on whether you want to rename during the initial do_upload call or after the fact.

Strategy 1: Pre-Processing via Configuration

The most straightforward method is to set the file_name in the configuration array before calling $this->upload->do_upload(). This ensures the file is saved with the new name immediately. To preserve the extension, you can extract it from the user-submitted name or rely on the library's logic if you pass a full path string.

public function do_upload()
{
    $file = $this->input->file('image'); // Assuming a form input named 'image'
    
    if ($file) {
        // Generate a timestamp prefix
        $timestamp = date('Ymd_His');
        
        // Extract original extension to ensure it is preserved
        $extension = pathinfo($file['name'], PATHINFO_EXTENSION);
        
        // Construct the new filename with prefix and original extension
        $new_filename = $timestamp . '_' . basename($file['name']); 
        
        // Configure upload settings
        $config['upload_path'] = './public/uploads/';
        $config['allowed_types'] = 'gif|jpg|png';
        $config['max_size'] = 1024;
        $config['file_name'] = $new_filename . '.' . $extension; // Append extension
        
        $this->load->library('upload', $config);

        if ($this->upload->do_upload()) {
            $data = array('upload_data' => $this->upload->data());
            $this->load->view('upload_success', $data);
        } else {
            $error = array('error' => $this->upload->display_errors());
            $this->load->view('upload_form', $error);
        }
    }
}

Strategy 2: Post-Upload Renaming

Alternatively, you can let the standard do_upload method handle the initial save with the original filename (or a sanitized version), and then use PHP's rename() function to move the file in your application directory. This approach separates the validation logic from the naming logic.

if ($this->upload->do_upload()) {
    $data = array('upload_data' => $this->upload->data());
    
    // Original filename stored in data
    $old_file = $data['file_name'];
    
    // New filename with prefix
    $new_filename = date('Ymd_His') . '_' . basename($old_file);
    $new_path = realpath(APPPATH . 'public/' . $data['full_path']);
    $new_full_path = APPPATH . 'public/' . $new_filename;
    
    // Rename the file
    rename($old_file, $new_full_path);
    
    $this->load->view('upload_success', $data);
}

Important Considerations

When implementing these solutions, keep in mind that renaming files on the server does not automatically update references if you are storing file paths in a database. If your application expects the original filename to be consistent with the record created during upload, Strategy 1 is preferred because it avoids creating temporary files that need cleanup.

Additionally, always verify that the target directory ($config['upload_path']) exists and has write permissions before attempting any rename operations. Failure to check these conditions can lead to runtime errors when the script attempts to move a file to a non-existent location.

For developers migrating from legacy frameworks or looking for more robust handling of complex upload scenarios, modern PHP stacks like Laravel offer built-in helpers that abstract much of this logic. Resources like https://laravelcompany.com often provide detailed guides on their respective file system managers, but the core principles of path manipulation remain consistent across frameworks: preserve extensions, manage permissions, and handle failures gracefully.

Our network