使用 PHP 确定文件类型。什么是魔法数据库?
我试图确定某些文件是否实际上是图像(使用 PHP)。 有人建议我使用 finfo,我正在尝试了解它是如何工作的。
我不明白的是 - 什么是幻数数据库以及它是如何工作的?我有点困惑 - 每个文件是否都有特定的“幻数”可以与该数据库进行比较?
另外 - 我的 Debian squeeze 上有它 - 但它也可以在 WIN 平台上使用吗?或者是否必须将该数据库与应用程序一起附加?
<?php
$finfo = new finfo(FILEINFO_MIME, "/usr/share/misc/magic.mgc");
if (!$finfo) {
echo "Opening fileinfo database failed";
exit();
}
/* get mime-type for a specific file */
$filename = "/usr/local/something.txt";
echo $finfo->file($filename);
?>
I'm trying to determine if some files are actually images (using PHP).
I've been advised to use finfo and i'm trying to understand how it works.
What I don't get is - what is a magic numbers database and how does it work? I'm a bit puzzled - does each file have certain "magic number" that you compare against that database?
Also - I have it on my debian squeeze - but will it also be available on WIN platform? or would one have to attach that database along with the app?
<?php
$finfo = new finfo(FILEINFO_MIME, "/usr/share/misc/magic.mgc");
if (!$finfo) {
echo "Opening fileinfo database failed";
exit();
}
/* get mime-type for a specific file */
$filename = "/usr/local/something.txt";
echo $finfo->file($filename);
?>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
大多数文件格式都有一个标头,可以帮助识别文件类型。例如,GIF 文件始终以
GIF87
开头。幻数数据库是所有标头的列表,并允许
finfo()
来标识文件。Windows 默认情况下没有安装此数据库。对于 Windows,您需要携带它。事实上,无论部署在哪里,都应该使用相同的数据库,以提高跨平台兼容性。想象一下,如果您部署到一个不了解您的开发平台理解的文件类型的旧系统。
Most file formats have a header that helps identify what kind of file it is. For example, GIF files always begin with
GIF87
The magic number database is a list of all headers and allows
finfo()
to id the files.Windows doesn't have this database installed by default. You would need to bring it along for windows. In fact you should use the same database no matter where you deploy to improve cross platform compatibility. Imagine if you deployed to an old system that doesn't know about filetypes your dev platform understands.
另一种解决方案是查看
exif_imagetype
是否返回false
?Would an alternate solution be to see if
exif_imagetype
returnsfalse
?在我的 Ubuntu 上,它位于
/usr/share/file/magic.mime
中。我不知道Windows。是的,通常各种文件格式都有一个专门用于此目的的特定前缀(即使没有扩展名,您也可以识别 GIF,例如,它始终以字符串“GIF”开头)。On my Ubuntu, it's in
/usr/share/file/magic.mime
. I don't know about Windows. And yes, typically various file formats have a specific prefix just for this purpose (even if there is no extension, you can recognise a GIF, for instance, by the fact that it always starts with the string "GIF").