Linux 上传文件上的 Finfo_file 以确定 MIME 类型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9458418/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Finfo_file on uploaded file to determine mime-type
提问by JimmyBanks
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? 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.
不幸的是,它finfo_file
似乎没有运行,我假设我$file
为此设置了不正确的以下设置,有没有办法可以$_FILE
像这样使用新上传的文件正确执行此操作?还是我以完全不正确的方式解决这个问题。使用我直接在另一个文件中预先设置的文件,设置$file="folder/file.doc"
工作正常。
采纳答案by Lawrence Cherone
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);
}
?>
回答by Jon Gallup
I know this is a bit old, but since you're using the $_FILES
super global, can you use the typekey of the file array (i.e. $_FILES['soup']['type']
) rather than having the server check once the file is uploaded?
我知道这有点旧,但是由于您使用的是$_FILES
超级全局,您可以使用文件数组的类型键(即$_FILES['soup']['type']
)而不是在文件上传后让服务器检查?
回答by Rotimi
I use the finfo()
buffer()
function as well as file_get_contents()
from the php platform as below
我使用该finfo()
buffer()
功能以及file_get_contents()
来自 php 平台的功能,如下所示
$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. for linux extension=fileinfo
. and in windows: php_fileinfo.dll
您需要打开php 5.3
或更高版本并确保finfo()
安装了扩展程序。对于 linux extension=fileinfo
。并在窗口中: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 类型的替代方法是将文件上传完全存储在文档根文件夹之外。