18

我试图确定上传文件的 mime 类型,我想使用 fileinfo(),这是我一直在尝试的,它不起作用:

$uploadedfile = $_FILES['soup']['tmp_name'];
if(isset($uploadedfile))
{
    $uploadedname = $_FILES['soup']['name'];
    $file=$uploadedsong;
    $file.=$uploadedname;
    $finfo = finfo_open(FILEINFO_MIME_TYPE); 
    $mime = finfo_file($finfo, $file);

不幸的是,finfo_file似乎没有运行,我假设我$file为此设置了以下错误,有没有办法可以使用$_FILE这样的新上传文件正确执行此操作?还是我以完全不正确的方式解决这个问题。使用我直接在另一个中预先设置的文件,并且设置$file="folder/file.doc"正常。

4

3 回答 3

33

您应该将路径传递给 finfo_file 函数而不是文件名。

<?php 
if (isset($_FILES['soup']['tmp_name'])) {
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mime = finfo_file($finfo, $_FILES['soup']['tmp_name']);
    if ($mime == 'application/msword') {
        //Its a doc format do something
    }
    finfo_close($finfo);
}
?>
于 2012-02-27T00:05:31.543 回答
1

我使用该finfo() buffer()函数以及file_get_contents()来自 php 平台的函数,如下所示

$finfo = new finfo(FILEINFO_MIME);
$mimetype = $finfo->buffer(file_get_contents($filename)); #gives you mime type

您需要开启php 5.3或更高版本,并确保已finfo()安装扩展程序。对于 linux extension=fileinfo。在 Windows 中:php_fileinfo.dll

你可以有一个可接受的 mime 类型数组,然后检查它是否存在于该数组中

$acceptedMime = [];
if(in_array($mimetype, $acceptedMime, true) === true){
  #mime type is valid. Proceed!
}

避免检查 mime 类型的另一种替代方法是将文件上传完全存储在文档根文件夹之外。

于 2017-12-04T10:45:42.830 回答
-1

我知道这有点旧,但是由于您使用的是$_FILES超级全局,您可以使用文件数组的类型键(即$_FILES['soup']['type'])而不是在文件上传后让服务器检查吗?

于 2015-01-08T16:18:12.657 回答