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