查找MIME类型使用文件或URL的PHP​​的所有文件格式文件格式、类型、文件、MIME

2023-09-11 10:29:31 作者:纵横天下

您好我在找找出在PHP MIME类型的任何本地文件或URL的最佳方式。 我已经试过PHP的 mime_content_type 的功能,但既然是去precated我正在寻找更好的解决方案PHP的所有文件格式。

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, "https://m.xsw88.com/allimgs/daicuo/20230911/3806.png.jpg");
    finfo_close($finfo);
    echo $mimetype;
}

以上code不工作对我来说,我只看到欢迎的output.I我不知道如果我在这里做得不对。

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.

下面code以某种方式在我的本地作品,但它并不适用于URL的工作。

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];

有一些工作围绕工作为(URL和本地)。什么是设置MIME类型的所有内容(图片,视频,文件等)比php.also mime_content_type功能是它推荐的其他最佳实践使用mime_content_type函数在PHP中,它是在PHP的最佳实践?

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 ?

推荐答案

找到了答案,

要查找的文件最好的方法是使用 PATH_INFO 对本地文件和URL。

To find the extension of the file best way is to use path_info for both local files and url.

$info     = pathinfo($filename);

$basename = $info['basename'];

$ext      = $info['extension'];

MIME类型创建数组

create an array for the mime type

$ MIMETYPES =阵列(MP4=>中的视频/ MP4); // - >的参见例这里和Here

//get the mime type for file
$type = isset($this->mime_types[$ext]) ? $this->mime_types[$ext] : "application/octet-stream";

以上code同时适用于URL和本地文件。

请注意:

那些与CDN MP4视频MIME类型的视频/ MP4问题苦苦挣扎 - 我有   取得我的class.s3.php文件中的变化 - 在MIME_TYPE> []数组,也   交叉检查与putObject()函数。

Those struggling with CDN mp4 video mime type video/mp4 issue - I had made a change in my class.s3.php file -> in mime_type[] array and also cross checked with putObject() function.

设置MIME类型始终是在编码端,而不是在AWS S3完成   斗,我们需要使用 AWS PHP类文件或SDK 做   操纵MIME类型或使核心类进行必要的修改   文件(例如,class.s3.php)

Setting of mime type is always done in coding side and not in AWS S3 bucket, We need to use AWS PHP Class file or sdk to do the manipulation in mime type or make the necessary changes in core class file (eg. class.s3.php )