开发者

How to implement a general Mime type correctly in PHP?

If you click view,you'll open that file in browser,

I've tried :

开发者_开发知识库
readfile('test.jpg');

But seems it fails in firefox.


If you want to get the mime-type for a file, you have at least two options, in PHP :

The first one is to use the (now deprecated) function mime_content_type :

Returns the content type in MIME format, like text/plain or application/octet-stream.


The second would be to use the new Fileinfo extension (Available as a PECL extension for PHP < 5.3, and integrated in PHP >= 5.3) ; the finfo_file function seems to be the one you'll need :

Returns a textual description of the contents of the filename argument, or FALSE if an error occurred.

And the given example (quoting) :

$finfo = finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension
foreach (glob("*") as $filename) {
    echo finfo_file($finfo, $filename) . "\n";
}
finfo_close($finfo);

Gives this kind of output :

text/html
image/gif
application/vnd.ms-excel

Which kind of corresponds to what you'll need to use for the Content-type HTTP header that your application might need to send ;-)


Just provide a link to that file and browser will do the rest. If this file is stored on your server you're probably looking for a script that will expose it to the outer world. This script should set up the correct MIME type and then readfile should do the trick.

<?php
header('Content-type: image/gif');
readfile('/path/to.your/file.gif');
exit();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜