代码之家  ›  专栏  ›  技术社区  ›  Abu Ayyub

在PHP中检查文件扩展名与mimetype之间的兼容性

  •  0
  • Abu Ayyub  · 技术社区  · 7 年前

    如何确保文件具有指定的扩展名和mimetype,因为它可能是更改文件扩展名的人。这可以用来防止文件扩展名相同但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 回复  |  直到 7 年前
        1
  •  1
  •   IVO GELOV    7 年前

    你应该这样做

    // 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;
    
    推荐文章