php - How to extract file extension from file with no extension with mime type octet-stream? -
i have large amount of files original file names have been replaced ids database. example, once name word_document.doc 12345. through process have lost original name.
i trying present these files download. person should able download file , view using it's original application. files in 1 of following formats:
- .txt (text)
- .doc (word document)
- .docx (word document)
- .wpd (word perfect)
- .pdf (pdf)
- .rtf (rich text)
- .sxw (star office)
- .odt (open office)
i'm using
$fhandle = finfo_open(fileinfo_mime); $file_mime_type = finfo_file($fhandle, $filepath);
to mime type , mapping mime type extension.
the problem running of files have mime type of octet-stream. i've read online , type seems miscellaneous type binary files. can't tell extension needs be. in cases works when set .wpd , cases doesn't. same goes .sxw.
symfony2 in 3 steps
1) mime_content_type
$type = mime_content_type($path); // remove charset (added of php 5.3) if (false !== $pos = strpos($type, ';')) { $type = substr($type, 0, $pos); } return $type;
2) file -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 type, error message return; } return $match[1];
3) finfo
if (!$finfo = new \finfo(fileinfo_mime_type, $path)) { return; } return $finfo->file($path);
after you've got mime-type can extension predefined map, example here or here
$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', );
Comments
Post a Comment