how to make sure that the file has a specified extension and mimetype, because it could be someone changing the file extension. this can be used to prevent file uploads with the same file extension but different mimetype.
this is my code, but the result is not what I want :
function mimeInfo($filename) {
$realpath = realpath( $filename );
if ( $realpath
&& function_exists( 'finfo_file' )
&& function_exists( 'finfo_open' )
&& defined( 'FILEINFO_MIME_TYPE' )
) {
// Use the Fileinfo PECL extension (PHP 5.3+)
return finfo_file( finfo_open( FILEINFO_MIME_TYPE ), $realpath );
}
if ( function_exists( 'mime_content_type' ) ) {
// Deprecated in PHP 5.3
return mime_content_type( $realpath );
}
return false;
}
function uploadAllows($pathfile){
$fileAllows = array(
"rar"=>"application/x-rar",
"xls"=>array(
"application/vnd.ms-office",
"application/x-msexcel",
"application/x-excel",
"application/excel",
"application/vnd.ms-excel",
)
);
$mimeInfo = mimeInfo($pathfile);
$file = pathinfo($pathfile);
$ext = $file['extension'];
if(count($fileAllows[$ext])>1){
if(in_array($mimeInfo, $fileAllows[$ext])){
return true;
}else{
return false;
}
}else{
if(in_array($mimeInfo, $fileAllows)){
return true;
}else{
return false;
}
}
}
expected 1:
1. extension must *.rar
2. mimetype must "application/x-rar"
expected 2:
1. extension must *.xls
2. mimetype must one of the spesific array
Thanks.
You should be doing it like this
// MIME types must be array even if there is only 1 of them
$fileAllows = array(
"rar"=>array("application/x-rar"),
"xls"=>array(
"application/vnd.ms-office",
"application/x-msexcel",
"application/x-excel",
"application/excel",
"application/vnd.ms-excel",
)
);
$mimeInfo = mimeInfo($pathfile);
$file = pathinfo($pathfile);
$ext = strtolower($file['extension']); // convert to lowercase
if(is_array($fileAllows[$ext])) return in_array($mimeInfo, $fileAllows[$ext]);
else return false;