Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Renaming an uploaded file in CodeIgniter

Tags:

codeigniter

Using CodeIgniter, I am trying to modify the name of the uploaded file to camelCase by removing any spaces and capitalizing subsequent words.

I am pretty sure that I can rename the file using the second parameter of move_uploaded_file but I don't even know where to look to figure out how to modify the name to camelCase.

Thanks in advance! Jon

like image 991
jgravois Avatar asked Nov 01 '10 22:11

jgravois


2 Answers

Check out CI's upload library:

http://www.codeigniter.com/user_guide/libraries/file_uploading.html

Let's first take a look at how to do a simple file upload without changing the filename:

$config['upload_path']   = './uploads/';
$config['allowed_types'] = 'jpg|jpeg|gif|png';

$this->upload->initialize($config);

if ( ! $this->upload->do_upload())
{
    $error = $this->upload->display_errors();
}   
else
{
    $file_data = $this->upload->data();
}

It's that simple and it works quite well.

Now, let's take a look at the meat of your problem. First we need to get the file name from the $_FILES array:

$file_name = $_FILES['file_var_name']['name'];

Then we can split the string with a _ delimiter like this:

$file_name_pieces = split('_', $file_name);

Then we'll have to iterate over the list and make a new string where all except the first spot have uppercase letters:

$new_file_name = '';
$count = 1;

foreach($file_name_pieces as $piece)
{
    if ($count !== 1)
    {
        $piece = ucfirst($piece);
    }

    $new_file_name .= $piece;
    $count++;
}

Now that we have the new filename, we can revisit what we did above. Basically, you do everything the same except you add this $config param:

$config['file_name'] = $new_file_name;

And that should do it! By default, CI has the overwrite $config param set to FALSE, so if there are any conflicts, it will append a number to the end of your filename. For the full list of parameters, see the link at the top of this post.

like image 71
treeface Avatar answered Oct 13 '22 05:10

treeface


$this->load->helper('inflector');
$file_name = underscore($_FILES['file_var_name']['name']);
$config['file_name'] = $file_name;

that should work too

like image 41
Abhishek Avatar answered Oct 13 '22 06:10

Abhishek