I want to get the exact MIME type basing on the file content, not its extension. I have used PHP methods and the API exposed by a module, but they return the MIME type basing on the file extension.
How do I get the MIME type from the file content?
Drupal Answers is a question and answer site for Drupal developers and administrators. It only takes a minute to sign up.
Sign up to join this communitySuppose you have the file binary source sent in a post request JSON encoded or any encoding method you could get the MIME type like in the following piece of code
$data = base64_decode(trim($_REQUEST['file']));
$finfo = finfo_open();
$mime_type = finfo_buffer($finfo, $data, FILEINFO_MIME_TYPE);
finfo_close($finfo);
// get file type png. jpg
$ext = $mime_type ? str_replace('image/', '', $mime_type) : 'png';
Hint:Its better to send the file mime type in the request as encoding and decoding may cause not get the MIME type.
Using file_get_contents
$buffer = file_get_contents($url);
$finfo = new finfo(FILEINFO_MIME_TYPE);
$ext = $finfo->buffer($buffer);
More information found here
Save the file using file_save_data to be a managed file and you could then use it as a field in any entity
You can easily get the MIME type of a file using mime_content_type() function.
$mime_type = mime_content_type($path_to_the_file);
I've just tested it on my local machine; placed a test.pdf
file in my home folder and renamed it giving it no and an incorrect extension. In both cases I got the right MIME type:
$ ls test.pdf $ drush eval 'var_dump(mime_content_type("/home/elin/test.pdf"))' string(15) "application/pdf" $ mv test.pdf test $ drush eval 'var_dump(mime_content_type("/home/elin/test"))' string(15) "application/pdf" $ mv test test.jpg $ drush eval 'var_dump(mime_content_type("/home/elin/test.jpg"))' string(15) "application/pdf" $ mv test.jpg test.png $ drush eval 'var_dump(mime_content_type("/home/elin/test.png"))' string(15) "application/pdf"