How can I detect the mime type with PHP when an actual file doesn't exist?
Is there a way to detect the mime type of a file without actually having an actual file, for example when you're generating the file and serving it as a download?
I'm currently using file extensio开发者_如何学Pythonn sniffing from here: http://www.php.net/manual/en/function.mime-content-type.php#87856
I was just wondering if there was another way short of actually creating the file on the server and using FileInfo, mime_content_type(), or file
Try the Fileinfo finfo_buffer()
function:
$filename = 'image.jpg';
$contents = file_get_contents($filename);
$finfo = finfo_open(FILEINFO_MIME_TYPE);
var_dump( finfo_buffer($finfo, $contents) ); // string(10) "image/jpeg"
You do say "short of actually creating the file," so this seems to meet your requirements even though it uses Fileinfo.
Have you tried writing it to a ramdisk - shouldn't have a significant speed penalty and you can use the standard functions
You might want to pipe it as such:
$type = `echo $FILE_CONTENTS | file -bi -`
READ: This is a bad idea. Do not do this. 'Command line injection' (thanks to Andrew Moore for point this out.)
If you know the type of file you're generating, just consult an array of known mime types and apply as appropriate.
you can check this :
$filename = 'image.jpg';
$filename2 = 'file.php';
echo mime_content_type($filename) . "<br>";
echo mime_content_type($filename2);
精彩评论