Reputation: 13
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 extension 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
Upvotes: 1
Views: 1114
Reputation: 845
you can check this :
$filename = 'image.jpg';
$filename2 = 'file.php';
echo mime_content_type($filename) . "<br>";
echo mime_content_type($filename2);
Upvotes: 0
Reputation: 57287
If you know the type of file you're generating, just consult an array of known mime types and apply as appropriate.
Upvotes: 0
Reputation:
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.
Upvotes: 2
Reputation: 1915
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.)
Upvotes: 0
Reputation: 28099
Have you tried writing it to a ramdisk - shouldn't have a significant speed penalty and you can use the standard functions
Upvotes: 0