You might all probably know that *nix systems treat myPic.jpg and MYpic.jpg different while windows systems don’t . So there’s always been a need to deal with filenames across different systems. We upload files which may be in lower case, uppercase or a mixture of both. This sometimes kills our valuable time and effort. To deal with files uploading, edit and delete if we always assume that file names are in lowercase, it’s lot better unless we have significant reasons to keep the case of the files intact. Codeigniter has a good uploading library which resides at /system/libraries/Upload.php. But unfortunately there’s no property of the uploading class that lets us to upload the file in lower case. So, the shortcut is to override the native method by your own library. When we initialize a library CI tries to find it within your application directory and then it’s System directory. So if we make a class MY_Upload extending CI_Upload, it can do the job. This is no trick, it’s documented on CI. So, now , we just need to override two functions in the CI_Upload class. These are _prep_filename and get_extension Here is how it looks
< ?php
// For overriding Native class to convert filenames to lowercase.
class MY_Upload extends CI_Upload
{
function _prep_filename($filename)
{
if (strpos($filename, '.') === false)
{
return $filename;
}
$parts = explode('.', $filename);
$ext = array_pop($parts);
$filename = array_shift($parts);
foreach ($parts as $part)
{
if ($this->mimes_types(strtolower($part)) === false)
{
$filename .= '.' . $part . '_';
}
else
{
$filename .= '.' . $part;
}
}
$filename .= '.' . $ext;
return strtolower($filename);
}
function get_extension($filename)
{
$x = explode('.', $filename);
return strtolower('.'.end($x));
}
}
The code can be downloaded from here
Unzip and put it in your /system/application/libraries directory.
Now for any upload you do using CI’s uploading class, will produce lowercased filenames.
3 Responses to Upload all your files in lowercase in Codeigniter
Shaun
June 10th, 2009 at 10:26 pm
I stumbled across this while searching for simple solutions to the same issue. I wanted to let you know that while your solution works, I’ve simplified it.
function _prep_filename($filename)
{
$filename = strtolower($filename);
return parent::_prep_filename($filename);
}
function get_extension($filename)
{
$filename = strtolower($filename);
return parent::get_extension($filename);
}
admin
June 11th, 2009 at 4:12 pm
Nice that you found a shortcut. I just wanted to keep the code similar to native lib and modify less keeping the objective intact.
Fabio
September 24th, 2011 at 6:54 am
Thanks