Search code examples
codeigniterfile-uploadfilenamesprefix

How can I add a prefix to a file name on upload in Codeigniter?


I have a file upload form on my website and would like to add a prefix to the beginning of the file name when a user uploads a photo.

I have set my configuration for the upload (see below) but am unsure how to set a prefix.

I preferably do not want to disturb the ['encrypt_name'] as this saves me time and effort making unique names but prefix to the beginning of the encrypted name. I will be adding the users id to the beginning.

    $config['upload_path'] = $upload_path;
    $config['allowed_types'] = 'gif|jpg|png';
    $config['max_size'] = '100';
    $config['max_width']  = '1024';
    $config['max_height']  = '768';
    $config['encrypt_name'] = true;

    $this->load->library('upload', $config);

Help always greatly appreciated.


Solution

  • It's probably easiest to get the filename using $this->upload->data(), and then using php rename() to add the id to the beginning.

    Something like this:

    $upload_data = $this->upload->data();
    rename(
        $upload_data['full_path'],
        $upload_data['file_path'].'/'.$user_id.'_'.$upload_data['orig_name']
    );