1

I'm writing an app using the CodeIgniter framework, and I'm utilizing the CI File Uploading class to upload image files to the server from a web form.

The files upload fine, but I would like to be able to save them under a different, unique name on the server. I would like to tell the File Upload class to save the files to the server using that different, unique filename for each file, but I haven't been able to figure out how to do so.

I've checked the CI docs for that class, and all I've found is that you can use the class to encrypt the filename, but I don't believe that will give me a unique filename, it just encrypts it.

I already have the functionality in the app that assigns a unique filename, so I just need to figure out how to get the File Uploading class to accept that alternate filename each time I save a file. Anyone know if it's possible to do that?

4 Answers 4

5

You can set configuration variables to achive both of the things you've asked. The following configuration variables can be found in the manual page

Setting a file name for your uploaded file

file_name None Desired file name

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.

Ensuring the filename is unique

overwrite FALSE TRUE/FALSE (boolean)

If set to true, if a file with the same name as the one you are uploading exists, it will be overwritten. If set to false, a number will be appended to the filename if another with the same name exists.

And you can set these configuration variables as follows

$config['file_name'] = 'myfile';
$config['overwrite'] = false;

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

// Alternately you can set preferences by calling the initialize function. Useful if you auto-load the class:
$this->upload->initialize($config);
5

If you want to change the upload file name, try this:

$newFileName = $_FILES['userfile']['name'];
// You can setfilename in config for upload
$config['file_name'] = $new_name;
0
1

You can set your filename:

$newFileName = $_FILES['some_field']['name'];
$fileExt = array_pop(explode(".", $newFileName));
$filename = md5(time()).".".$fileExt;

//set filename in config for upload
$config['file_name'] = $filename;

Hope it helps

1
  • 1
    I've just checked the Upload class, starting on line 218 it uses the uploaded files extension if one isn't given. Therefore you don't need to use the array_pop bit in your code.
    – Grant J
    Jul 12, 2013 at 14:56
0

If you Want Change upload file name :

$fname = "Set File Name What You Want";


$config['file_name'] = $fname;
$config['overwrite'] = false;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.