11

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

3 Answers 3

14

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Great answer! That helps me alot.
I'm trying to switch from using the _ delimiter to using the .. In terms of exploding on the . delimiter, a file name using . instead of _ makes more sense. However, for some reason the save isn't taking my . names, but insists on using _. Anybody run into this kind of problem renaming images with CI?
3
$this->load->helper('inflector');
$file_name = underscore($_FILES['file_var_name']['name']);
$config['file_name'] = $file_name;

that should work too

Comments

0
$file_name = preg_replace('/[^a-zA-Z]/', '', ucwords($_FILES['file_var_name']['name']));

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.