PHP报告错误的MIME类型 [英] PHP reports incorrect MIME type
问题描述
我正在设计一个简单的PHP脚本,以允许上载* .cpp源文件.作为一种基本的安全措施,在将临时文件移到永久位置之前,我会先检查其MIME类型.在终端(在Mac OS X上)中运行file --mime myfile.cpp
时,它显示为text/x-c
.但是由于某种原因,服务器将其视为application/octet-stream
.在/etc/mime.types
中,在text/x-c++src
下有"cpp"扩展名,这使我相信这是Mac上的MIME类型问题.
I am designing a simple PHP script to allow uploads of *.cpp source files. As a basic security measure, I check the MIME type of the temporary file before moving it to a permanent location. When I run file --mime myfile.cpp
in Terminal (on Mac OS X) it shows up as text/x-c
. Yet the server sees it as a application/octet-stream
for some reason. In /etc/mime.types
the "cpp" extension is there under text/x-c++src
which leads me to believe it's an issue with MIME types on Mac.
我在Ubuntu上尝试了相同的过程,并且工作正常(显示为text/x-c++src
).我在两台计算机上都使用Chrome.
I've tried the same procedure from Ubuntu and it works fine (it shows up as text/x-c++src
). I am using Chrome on both computers.
这本身并不是一个编程问题,但是可能有一些我不熟悉的PHP技巧.
It's not exactly a programming question per se, but there may be some PHP trick to this that I'm not familiar with.
$temp_file=$_FILES["file"]["type"];
if(($temp_file!="text/x-c++src")||($temp_file!="text/x-c")) {
echo "<p style=\"color:red;font-style:italic\">Please upload a valid C++ file.</p>";
}
推荐答案
$_FILES['userfile']['type']
包含浏览器发送的MIME类型(在上传过程中).您可以使用它,但不能信任它.
The $_FILES['userfile']['type']
contains the mime-type which the browser sent (during the upload). You can use it, but you cannot trust it.
尝试使用以下方法从$_FILES['userfile']['tmp_name']
获取哑剧类型:
Try getting the mime-type from $_FILES['userfile']['tmp_name']
using:
$mime = mime_content_type($tmp_name);
// or, as this is deprecated:
$info = new finfo(FILEINFO_MIME_TYPE);
$mime = $info->file($tmp_name);
或者,您可以通过strrchr($_FILES['userfile']['name'], '.')
中原始文件名的扩展名进行猜测.
Or, you can guess by the original file-name's extension in strrchr($_FILES['userfile']['name'], '.')
.
这篇关于PHP报告错误的MIME类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!