在这样的时候,官方的HTTP规范总是有帮助的。从
RFC 2616 7.2.1(我的强调添加):
Any HTTP/1.1 message containing an entity-body SHOULD include a Content-Type header field defining the media type of that body. If and only if the media type is not given by a Content-Type field, the recipient MAY attempt to guess the media type via inspection of its content and/or the name extension(s) of the URI used to identify the resource. If the media type remains unknown, the recipient SHOULD treat it as type “application/octet-stream”.
您的问题的原因是接受文件上传的服务器本身不知道已上传的文件的类型。为什么?因为它依赖于发送文件的HTTP消息来指定Content-Type头来确定确切的mime类型。浏览器可能没有发送Content-Type头,并且服务器已经根据上面的官方HTTP规范摘录假设了应用/八位字节流。也有可能客户端上传文件选择不确定它正在上传的文件的MIME类型,并发送Content-Type:application / octet-stream头本身。
$_FILES['userfile']['type']
The mime type of the file, if the browser provided this information. An example would be “image/gif”. This mime type is however not checked on the PHP side and therefore don’t take its value for granted.
所以你可以看到,即使指定了$ _FILES [‘userfile’] [‘type’],它只对应于客户端发送的Content-Type头。此信息可以很容易伪造,不应依赖。如果您需要确保上传的文件是特定类型的文件,则必须自行验证。