CodeIgniter- How to change uploaded file name

In CodeIgniter(Version-1.7.1), Normally we can’t change  or rename uploaded filename. Don’t understand what i am talking about. lets clear it, suppose  that u want to upload a file named “ABC” (Name of your file in your PC) to server by changing the name from “ABC to “XYZ” . Then WHAT?????

To change the uploaded file name you have to modify CodeIgniter Upload class which can be found at

system\libraries\Upload.php

then go to line number 190 and insert comment tag before the line which you have to modify

or simply you have to find the line which is shown here


// Set the uploaded data as class variables
 $this->file_temp = $_FILES[$field]['tmp_name'];        

 //insert a single comment tag to the following line
 //$this->file_name = $this->_prep_filename($_FILES[$field]['name']);

 $this->file_size = $_FILES[$field]['size'];        
 $this->file_type = preg_replace("/^(.+?);.*$/", "\\1", $_FILES[$field]['type']);
 $this->file_type = strtolower($this->file_type);
 $this->file_ext     = $this->get_extension($_FILES[$field]['name']);

Next add the modiefied code after the last line which is shown here


$this->file_ext     = $this->get_extension($_FILES[$field]['name']);
 //Add the Modifide Code here
 if (empty($this->file_name)){
 $this->file_name = $this->_prep_filename($_FILES[$field]['name']);
 }
 else{
 $this->file_name = $this->_prep_filename($this->file_name.$this->file_ext);    
 }

Now when you load upload class then provide the name and do_upload function upload  your file by setting the name you provided.

</pre>
//Provide your desire file name

$config['file_name']='XYZ';

$config['upload_path'] = './uploads/';
 $config['allowed_types'] = 'gif|jpg|png';
 $config['max_size']    = '100';
 $config['max_width']  = '1024';
 $config['max_height']  = '768';

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

Thats all…

4 thoughts on “CodeIgniter- How to change uploaded file name

Leave a comment