简体   繁体   中英

How do I detect MIME type via a file handle in PHP?

I'm on 5.4 and looking to detect a mime type from my file handle. I know I can save off a file and then use functions by passing strings, but we want to avoid using strings. So is there a way without any strings?

Instead of passing a file handle or a string, pass an SplFileObject . Using this, you get OO access to the file without directly calling file system functions. Functions that require a pathname can still by used by calling ->getRealPath() on the object.

$finfo     = new finfo(FILEINFO_MIME_TYPE); 
$mime_type = $finfo->file( $fileObject->getRealPath() );

If your PHP installation supports Fileinfo :

$finfo = new finfo;
$mime = $finfo->file($file, FILEINFO_MIME);
finfo_close($finfo);

Where $file would be the full path to the file. $mime will then contain it's MIME type, for example 'image/jpeg' for a JPG image or 'text/x-php' for a PHP script.

Use fileinfo

$fileinfo = finfo_file($finfo, $file, FILEINFO_MIME);     
finfo_close($finfo);

Or, you could do it the object-oriented way:

$finfo = new finfo();
$file = '/path/to/file/';
$fileinfo = $finfo->file($file, FILEINFO_MIME);

Use stream_get_meta_data to extract uri

$mime = mime_content_type(
    stream_get_meta_data($fh)['uri']
);

Where $fh is our filehandle

AFAIK there's nothing inside a file content bytes that specifically tell the mime type. You have two options:

  1. Detect the contents inspecting the bytes (actually I don't think this should be considered an option, given the difficulty and the performance implications involved).
  2. Detect the mime type inspecting the file extension (if such extension exists): this method isn't error-proof, but is the accepted way of doing this (IMO). If the file haven't any extension, then you have a problem that can't be easily solved.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM