I upload image files with codeigniter to my website using:
$uploaded = $this->upload->data();
and getting the filename in this way:
$uploaded['file_name'];
I want to change this filename adding “_thumb” before extension and after the name. Like ‘sda8sda8fa8f9.jpg’ to ‘sda8sda8fa8f9_thumb.jpg’. Since I need to keep hashed name, what is the simpliest way to do this?
Advertisement
Answer
When configuring CI’s file uploader, you can pass a file_name
option to the class. That will change the name of the uploaded file. Here’s the description from the docs:
If set CodeIgniter will rename the uploaded file to this name. The extension provided in the file name must also be an allowed file type. If no extension is provided in the original file_name will be used.
And an example:
$this->load->library('upload', ['file_name' => 'new-file-name.ext']); $this->upload->do_upload('file_field_name');
So, you want to modify the uploaded file’s name. The uploaded filename can be accessed from PHP’s $_FILES
array. First, we figure out the new name, then we hit CI’s upload library. Assuming that the fieldname is fieldname
:
// Modify the filename, adding that "_thumb" thing // I assumed the extension is always ".jpg" for the sake of simplicity, // but if that's not the case, you can use "pathinfo()" to get info on // the filename in order to modify it. $new_filename = str_replace('.jpg', '_thumb.jpg', $_FILES['fieldname']['name']); // Configure CI's upload library with the filename and hit it $this->upload->initialize([ 'file_name' => $new_filename // Other config options... ]); $this->upload->do_upload('fieldname');
Please note that the original filename (that from the $_FILES['fieldname']['name']
) comes from the user’s browser. It’s the actual filename on user’s device. As you decided to depend on it in your code, always treat it as tainted.