Thank you for sharing this code devbro! I like your library-extension. However, I did make some changes too. If you don’t mind, I’ll post them here. :red:
I added a few lines to the function file_max_size() to make sure that the $max_size variable actually is an integer.
// Check if $max_size is valid
if (preg_match("/[^0-9]/", $max_size))
{
return FALSE;
}
And I changed the function file_allowed_type() in order to make it possible to allow a few file-types. The file-types are seperated by commas. So a validation rule in my controller can look like file_allowed_type[word,jpeg].
// FUNCTION: file_allowed_type
// Checks if an uploaded file has a certain file type
//
// @Author: devbro (21 July 2009)
// @Author: chicken's egg (2 August 2009) (edited)
//
// @access public
// @param $file array File-information
// @param $type string Allowed filetype(s)
// @return bool
function file_allowed_type($file,$sType)
{
/*
three types allowed:
1. mime type image/gif
2. general mime type image application
3. file ext pdf,xls
*/
// Create an array of allowed filetype
$aTypes = explode(',',$sType);
// Validate file-type
foreach($aTypes AS $key => $sType)
{
$sType = trim($sType);
if(strpos($file['type'],$sType)!==FALSE)
{
return TRUE;
}
}
// File-type not found? Invalid filetype
$this->set_message('file_allowed_type',"%s cannot be {$file['type']}.(should be %s)");
return FALSE;
}
Which brings me to a question. Why are we using $file[‘type’]? I discovered that the value of $file[‘type’] - at least on my Windows XP computer - is prescribed by the file-extension. So this function gives the same results, but is easier to handle as most of us do know file-extensions better then mime-types.
// FUNCTION: file_allowed_type
// Checks if an uploaded file has a certain extension.
//
// @Author: chicken's egg (2 August 2009)
//
// @access public
// @param $file array File-information
// @param $type string Allowed filetype(s)
// @return bool
function file_allowed_type($file,$sType)
{
// Create an array of allowed file-type
$aTypes = explode(',',strtolower(trim($sType)));
// Take the extension of the uploaded file
$sExtension = strtolower(substr($file['name'],(strrpos($file['name'],".") + 1)));
// Check if it is an allowed filetype
if(in_array($sExtension,$aTypes))
{
return TRUE;
}
// Filetype not found? Invalid filetype
$this->set_message('file_allowed_type',"%s cannot be {$file['type']}.(should be %s)");
return FALSE;
}