我正在将图像从我的Android应用程序上传到我的服务器。该应用程序使用安卓相机意图,通过PHP脚本上传是可以的。
我想验证上传的文件是否是真实图像,我不是在检查扩展名,而是在检查 mimetype(我想这是最好的方法,如果我错了,请告诉我)。
我正在使用Slackware Linux Apache服务器,我正在尝试以下代码:
....
$finfo = finfo_open(FILEINFO_MIME, '/etc/httpd/magic');
....
fwrite($fp, finfo_file($finfo, "file.jpg"));
....
但是我得到了"应用程序/八位字节流;字符集=二进制"而不是"图像/JPEG;charset=binary",它来自"file -i file.jpg"(shell命令)。
怎么了?
使用 $finfo = finfo_open(FILEINFO_MIME); 而不是另一行求解。我认为默认的魔术文件与我指定的不同。
如 www.php.net/manual/en/ref.fileinfo.php 所述:
<?php
function is_jpg($fullpathtoimage){
if(file_exists($fullpathtoimage)){
exec("/usr/bin/identify -format %m $fullpathtoimage",$out);
//using system() echos STDOUT automatically
if(!empty($out)){
//identify returns an empty result to php
//if the file is not an image
if($out == 'JPEG'){
return true;
}
}
}
return false;
}
?>
或者
,如果你有执行权限并且想使用"hacky"解决方案,你可以简单地做你已经做过的事情(使用file -i path
和shell_exec
):
<?php
function shell_get_mime_type($path) {
if (is_readable($path)) {
$command = 'file -i "' . realpath($path) . '"';
$shellOutput = trim(shell_exec($command));
//eg. "nav_item.png: image/png; charset=binary"
if (!empty($shellOutput)) {
$colonPosition = strpos($shellOutput, ':');
if ($colonPosition !== false) {
return rtrim(substr($shellOutput, $colonPosition + 1));
}
return $shellOutput;
}
}
return false;
}
?>
尝试使用函数mime_content_type()
。