如何阅读在PHP上传文件的标题? [英] How to read header of a file uploaded in PHP?

查看:165
本文介绍了如何阅读在PHP上传文件的标题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们可以在PHP中读取一个文件的头文件信息,以确定上传文件的类型吗?

我不想依赖 $ _ FILES ['control_name_from_client'] ['type']。我们知道这个属性通过读取文件的扩展名来确定文件类型。 b $ b

如果用户重命名 test.jpg - > test.xls ,该怎么办?在这种情况下, $ _ FILES ['control_name_from_client'] ['type'] 将显示类型为 application / vnd.ms-excel 而不是 image / jpeg 。这是很自然的,如果需要执行代码来读取XLS文件来获取数据以进行一些处理,那么这可能会造成问题。



有什么建议吗?

解决方案

试试 finfo_file() 即可。你必须调用它传递文件路径。例如:

  $ finfo = finfo_open(FILEINFO_MIME_TYPE); 
$ mime = finfo_file($ finfo,$ _FILES ['control_name_from_client'] ['tmp_name']);
finfo_close($ finfo);

您需要 Fileinfo 扩展名。正如PHP手册所说:
$ b


这个模块中的函数试图通过查找某个元素来猜测文件的内容类型和编码, 字节序列在文件中的特定位置。虽然这不是一个防弹的办法,启发式使用做了很好的工作。


Can we read the header information of a file in PHP to determine the type of file uploaded?.

I don't want to rely on $_FILES['control_name_from_client']['type']. As we know that this property determines the file type by reading the extension of the file uploaded.

What if the user renames, say test.jpg -> test.xls. In that case, $_FILES['control_name_from_client']['type'] will show the type as application/vnd.ms-excel instead of image/jpeg. It is but natural this can create problems if a code has to be executed which reads the XLS file to fetch data for some processing.

Any suggestions please?

解决方案

Try finfo_file(). You have to call it passing the filepath. Example:

$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $_FILES['control_name_from_client']['tmp_name']);
finfo_close($finfo);

You need the Fileinfo extension. As PHP manual says:

The functions in this module try to guess the content type and encoding of a file by looking for certain magic byte sequences at specific positions within the file. While this is not a bullet proof approach the heuristics used do a very good job.

这篇关于如何阅读在PHP上传文件的标题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆