Search code examples
phpmime-types

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


Solution

  • 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.