Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
257 views
in Technique[技术] by (71.8m points)

PHP验证上传文件

$finfo    = finfo_open( FILEINFO_MIME );
$mimetype = finfo_file( $finfo , $this->fileInfo['tmp_name'] );
if ( $mimetype == "audio/mpeg; charset=binary" )
{
    return TRUE;
}
else
{
    $this->error = "请上传合法文件";
    return FALSE;
}

为什么有些mp3文件的$mimetype是application/octet-stream; charset=binary,有些是audio/mpeg; charset=binary

application/octet-stream; charset=binary是否安全,或者怎样进一步验证上传的文件是安全的音频文件?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

以前,我用 python 写了一个上传文件的白名单,利用白名单内设置的16进制的头,进行比对。希望能给你一个参考。

def image_type_list():
    """
    支持文件类型
    用16进制字符串的目的是可以知道文件头是多少字节
    各种文件头的长度不一样,少半2字符,长则8字符
    :return:
    """
    return {
        "FFD8FF": "JPEG",
        "89504E47": "PNG",
        "47494638": "GIF",
        "504B0304": "ZIP",
        "25504446": "PDF",
        "D0CF11E0": "DOC,XLS",
        '504B03': "DOCX,XLSX",
        '52617221': "TAR",
        '44656C69766572792D646174653A': 'EML'
    }


def bytes2hex(bytes):
    """
    字节码转16进制字符串
    :param bytes:
    :return:
    """
    num = len(bytes)
    hexstr = u""
    for i in range(num):
        t = u"%x" % bytes[i]
        if len(t) % 2:
            hexstr += u"0"
        hexstr += t
    return hexstr.upper()


def is_image_file_type(binfile):
    """
    # 获取文件类型
    :param binfile:open(filename, 'rb') # 必需二制字读取
    :return:
    """
    is_image = False
    tl = image_type_list()
    for hcode in tl.keys():
        numOfBytes = len(hcode) / 2  # 需要读多少字节
        hbytes = struct.unpack_from("B" * numOfBytes, binfile[0:numOfBytes])
        f_hcode = bytes2hex(hbytes)
        if f_hcode == hcode:
            is_image = True
            break
    return is_image

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...