Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

amazon web services - Find Mime type of file or url using php for all file format

Hi I am looking for best way to find out mime type in php for any local file or url. I have tried mime_content_type function of php but since it is deprecated I am looking for better solution in php for all file format.

mime_content_type — Detect MIME Content-type for a file ***(deprecated)***

I have already tried below function

echo 'welcome';
if (function_exists('finfo_open')) {
    echo 'testing';
    $finfo = finfo_open(FILEINFO_MIME);
    $mimetype = finfo_file($finfo, "http://4images.in/wp-content/uploads/2013/12/Siberian-Tiger-Running-Through-Snow-Tom-Brakefield-Getty-Images-200353826-001.jpg");
    finfo_close($finfo);
    echo $mimetype;
}

Above code is not working for me, I am only seeing welcome for output.I am not sure if I am doing something wrong here.


Below code works somehow in my local but it does not work for urls.

$file = './apache_pb2.png';
$file_info = new finfo(FILEINFO_MIME);  // object oriented approach!
$mime_type = $file_info->buffer(file_get_contents($file));  // e.g. gives "image/jpeg"
$mime  = explode(';', $mime_type);
print $mime[0];

Is there some work around which work for both(url and local).what is the best practice to set mime type for all contents (image, video, file etc.) other than mime_content_type function in php.also is it recommended to use the mime_content_type function in php, Is it best practice in php ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Make use of file_info in PHP with FILEINFO_MIME_TYPE flag as the parameter.

[Example taken as it is from PHP Manual]

<?php
$finfo = finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension
foreach (glob("*") as $filename) {
    echo finfo_file($finfo, $filename) . "
";
}
finfo_close($finfo);
?>

OUTPUT :

text/html
image/gif
application/vnd.ms-excel

EDIT :

You need to enable the extension on your PHP.ini

;extension=php_fileinfo.dll

Remove the semicolon from that line and restart your webserver and you are good to go.
Installation Doc.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...