php - 如何从 mime 类型八位字节流的没有扩展名的文件中提取文件扩展名?

标签 php mime-types fileinfo

我有大量文件,它们的原始文件名已被我数据库中的 ID 替换。例如,以前的名称 word_document.doc 现在是 12345。通过一个过程,我失去了原来的名字。

我现在正尝试提供这些文件以供下载。该人应该能够下载该文件并使用其原始应用程序查看它。这些文件都是以下格式之一:

  • .txt(文本)
  • .doc(word文档)
  • .docx(word文档)
  • .wpd(完美词)
  • .pdf (PDF)
  • .rtf(富文本)
  • .sxw(星级办公室)
  • .odt(开放办公室)

我在用

$fhandle = finfo_open(FILEINFO_MIME);
$file_mime_type = finfo_file($fhandle, $filepath);

获取 MIME 类型,然后将 MIME 类型映射到扩展名。

我遇到的问题是某些文件的 MIME 类型为 octet-stream。我在网上看过,这种类型似乎是二进制文件的杂项类型。我不能轻易说出扩展需要什么。在某些情况下,当我将它设置为 .wpd 时它会起作用,而在某些情况下它不会。 .sxw 也是如此。

最佳答案

Symfony2分三步完成

1) mime_content_type

$type = mime_content_type($path);

// remove charset (added as of PHP 5.3)
if (false !== $pos = strpos($type, ';')) {
    $type = substr($type, 0, $pos);
}

return $type;

2) 文件-b --mime

ob_start();
passthru(sprintf('file -b --mime %s 2>/dev/null', escapeshellarg($path)), $return);
if ($return > 0) {
    ob_end_clean();

    return;
}

$type = trim(ob_get_clean());
if (!preg_match('#^([a-z0-9\-]+/[a-z0-9\-\.]+)#i', $type, $match)) {
    // it's not a type, but an error message
    return;
}

return $match[1];

3) 信息

if (!$finfo = new \finfo(FILEINFO_MIME_TYPE, $path)) {
    return;
}

return $finfo->file($path);

获得 mime 类型后,您可以从预定义映射中获取扩展名,例如从 herehere

$map = array(
    'application/msword' => 'doc',
    'application/x-msword' => 'doc',
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document' => 'docx',
    'application/pdf' => 'pdf',
    'application/x-pdf' => 'pdf',
    'application/rtf' => 'rtf',
    'text/rtf' => 'rtf',
    'application/vnd.sun.xml.writer' => 'sxw',
    'application/vnd.oasis.opendocument.text' => 'odt',
    'text/plain' => 'txt',
);

关于php - 如何从 mime 类型八位字节流的没有扩展名的文件中提取文件扩展名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31410148/

相关文章:

php - 发送 "var_dump"到 FireBug 控制台

php - Mysqli Connect 上的未知数据库...但它确实存在

php - 为什么我的 while 循环在主文件中工作,但如果我尝试从单独的文件中包含它则不起作用?

cocoa - 使用 Cocoa (OS X) 进行内存中 mime 类型检测?

c++ - QWebPage,获取mime类型

c# - DirectoryInfo GetFiles TOP 编号

php - 在循环中使用 curl 从数据库中获取的数字向客户端发送数据

ruby-on-rails - 在 Rails 开发环境中为 .ogv 文件设置 Mime 类型

javascript - 如何在js中获取文件创建或更新日期

php - 从base64编码的字符串中获取图像信息