Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add MIME type knowledge to PHP

Tags:

php

mime

I know of the UNIX command file to detect the mime type of a file, which I can execute via PHP (like here):

$content_type = exec("file -bi " . escapeshellarg($filepath));

And I am also aware of

$fi = new finfo();
echo $fi->file($filename, FILEINFO_MIME_TYPE) . PHP_EOL;

and

echo mime_content_type($filename) . PHP_EOL;

Both PHP built-in solutions produce the same output. However, the Linux file command knows some formats more.

AMR audio files were reported as application/octet-stream with all three methods. Then I added the file magic to the database of the file command:

$ cat /etc/magic
0   string  #!AMR\n Adaptive Multi-Rate Audio Codec
!:mime  audio/amr

$ file -bi test115.amr 
audio/amr; charset=binary

However, PHP still reports application/octet-stream.

I thought the PHP-builtin and file use the same database somehow. How can I train PHP to know the MIME type of an AMR file?

like image 291
rexkogitans Avatar asked May 22 '26 13:05

rexkogitans


1 Answers

PHP seems to use their own, bundled database for fileinfo lookups; you can override this behaviour by either adding the second parameter to the new finfo call, or by setting the MAGIC env var.

From the docs:

Note: Generally, using the bundled magic database (by leaving magic_file and the MAGIC environment variables unset) is the best course of action unless you specifically need a custom magic database.

http://php.net/manual/en/function.finfo-open.php

like image 158
Duroth Avatar answered May 24 '26 02:05

Duroth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!