tags:

views:

52

answers:

2

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

I've tried :

readfile('test.jpg');

But seems it fails in firefox.

+1  A: 

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();
RaYell
What if the file is .pdf?Is there a general solution?
search MIME Type.
deerchao
+1  A: 

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 ;-)

Pascal MARTIN
If there are many concurrent users you might want to consider caching the result somehow since mime magic pattern testing isn't the "cheapest" of functions ;-)
VolkerK
finfo_open Failed to load magic database,php 2.5
Well, there is some kind of "magic database" you have to put in the right place (I tried a couple of times, it's not that easy to set up, but not **that** hard either) ;; there are a couple of informations on http://www.php.net/manual/en/function.finfo-open.php that might guide you a bit farther.
Pascal MARTIN