php-imap icon indicating copy to clipboard operation
php-imap copied to clipboard

$attachment->getExtension() return wrong file name extension

Open mdemori opened this issue 3 years ago • 0 comments

Hi,

I'm not sure if this is:

  • A bug
  • An intended Behavior
  • A documentation error
  • A wrong named function

The problem from my point of view is that the function return the MIME type of the file and NOT the real file name extension. As example, I've a case where I try to get all csv file attachment from a message but my function return nothing, this happen because the file name extension is csv but the extension type returned by getExtension() is txt (because the mime type of csv return txt) so my check fail. I did something like this:

$attachmentList = $currentMessage->getAttachments();
foreach ($attachments as $attachment){
  if($attachment->getExtension() === 'csv'){
   //some actions
  }
}

The mime type obviously is correct because a csv file is a simple txt file with a ".csv" extension. So, technically the result is correct (mime_content_type return "text/plain" as result) but the file extension is not txt... so at this point I'm back to my initial consideration.. I don't know if this is really a bug or something else.

As reference for other people that can find this problem, I solved in an "old fashion way" :D

    function getAttachmentFileNameInfo(\Webklex\PHPIMAP\Attachment $attachment): array
    {

        $result = [
            'dirname' => '',
            'basename' => '',
            'extension' => '',
            'filename' => ''
        ];

        $attachmentInfo = $attachment->getAttributes();
        if (
            !array_key_exists('name', $attachmentInfo)
            && (trim($attachmentInfo['name']) !== '')
        ) {
            return $result;
        }
        return pathinfo($attachmentInfo['name']);
    }

//code that check for attachments
$attachmentList = $currentMessage->getAttachments();
foreach ($attachments as $attachment){
  if (
         !array_key_exists('name', $attachmentInfo)
          && (trim($attachmentInfo['name']) !== '')
      ) 
     {
                continue;
      }
  $fileNameInfo = getAttachmentFileNameInfo($attachment);
  if($fileNameInfo['extension'] === 'csv'){
   //some actions
  }
}

mdemori avatar Jul 01 '22 08:07 mdemori