简体   繁体   English

上传文件中的Finfo_file确定mime-type

[英]Finfo_file on uploaded file to determine mime-type

Im trying to determine the mime-type of an uploaded file, i want to use fileinfo(), this is what ive been trying, it isnt working: 我试图确定上传文件的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);

Unfortunately the finfo_file doesnt seem to be running, Im assuming i have the following $file set incorrectly for this, is there a way i can do this properly with a newly uploaded file using $_FILE like this? 不幸的是finfo_file似乎没有运行,我假设我有以下$file设置不正确,有没有办法我可以使用$_FILE像这样正确地使用新上传的文件吗? or am i going at this problem the completely improper way. 或者我是以完全不正当的方式解决这个问题。 Using a file i have pre-set in another directly, and setting $file="folder/file.doc" works properly. 使用我直接在另一个文件中预先设置的$file="folder/file.doc" ,并设置$file="folder/file.doc"正常工作。

You should be passing the path to the finfo_file function not the filename. 您应该将路径传递给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);
}
?>

I use the finfo() buffer() function as well as file_get_contents() from the php platform as below 我使用finfo() buffer()函数以及php平台的file_get_contents() ,如下所示

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

you need to be on php 5.3 or higher and make sure you have the finfo() extension installed. 你需要在php 5.3或更高版本上,并确保你安装了finfo()扩展。 for linux extension=fileinfo . 对于linux extension=fileinfo and in windows: php_fileinfo.dll 在windows中: php_fileinfo.dll

you can have an array of accepted mime types and then check if it exists in that array 您可以拥有一组已接受的mime类型,然后检查它是否存在于该数组中

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

Another alternative to avoid having to check mime types would be to store file uploads completely out of the document root folder. 避免必须检查mime类型的另一种方法是将文件上传完全存储在文档根文件夹之外。

我知道这$_FILES ,但是因为你使用$_FILES超级全局,你可以使用文件数组的类型键(即$_FILES['soup']['type'] )而不是服务器文件上传后检查?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM