0

I am trying to detect the correct MIME type for XLSX files on upload but nothing seems to work for me so far.

$allowed_mimes = [
    'pdf'  => 'application/pdf',
    'png'  => 'image/png',
    'jpg'  => 'image/jpeg',
    'xls'  => 'application/vnd.ms-excel',
    'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    'doc'  => 'application/msword',
    'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    'rtf'  => 'application/rtf',
    'odt'  => 'application/vnd.oasis.opendocument.text',
];
$finfo      = new finfo(FILEINFO_MIME_TYPE);
$is_allowed = array_search($finfo->file($attachment['tmp_name']), $allowed_mimes, true);
if (false === $is_allowed) {
    return [
        'error'   => true,
        'title'   => 'File format not supported',
        'message' => 'This file format is not supported yet. Format: ' . $finfo->file($attachment['tmp_name']),
    ];
}

I have already used AddType in .htaccess file:

AddType application/vnd.openxmlformats-officedocument.spreadsheetml.sheet .xlsx

This doesn't seem to work for me either. I am on a VPS (Ubuntu) using Apache, I have checked the /etc/mime.types file and application/vnd.openxmlformats-officedocument.wordprocessingml.document is present there. Also /usr/share/mime/application/vnd.openxmlformats-officedocument.wordprocessingml.document.xml file exists. I am not sure what the issue is.

Antti29
  • 2,953
  • 12
  • 34
  • 36

1 Answers1

0

Why not to use mime_content_type? Note, that you have to provide correct filename with full path. This code works fine for me:

$allowed_mimes = [
    'pdf'  => 'application/pdf',
    'png'  => 'image/png',
    'jpg'  => 'image/jpeg',
    'xls'  => 'application/vnd.ms-excel',
    'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    'doc'  => 'application/msword',
    'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    'rtf'  => 'application/rtf',
    'odt'  => 'application/vnd.oasis.opendocument.text',
];
$is_allowed = array_search(mime_content_type($attachment['tmp_name']), $allowed_mimes, true);
if (!$is_allowed) {
    return [
        'error'   => true,
        'title'   => 'File format not supported',
        'message' => 'This file format is not supported yet. Format: ' . mime_content_type($attachment['tmp_name']),
    ];
}