检查php中带有mimetype的文件扩展名之间的兼容性

时间:2018-07-22 11:12:22

标签: php arrays mime-types file-extension fileinfo

如何确保文件具有指定的扩展名和mimetype,因为可能是有人更改了文件扩展名。这可以用来防止文件扩展名相同但模仿类型不同的文件上传。

这是我的代码,但结果不是我想要的:

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;
            }
        }
}

预期1:

1. extension must *.rar
2. mimetype must "application/x-rar"

预期2:

1. extension must *.xls
2. mimetype must one of the spesific array

谢谢。

1 个答案:

答案 0 :(得分:1)

您应该这样做

// 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;