PHPMailer - Attachment has no extension

0

Well, when sending my attachment using PHPMailer, if I do not add an extension after the variable, I can not get the extension of the selected file ie:

$mail->addAttachment($uploadfile) should send the file, giving its name and type, but sends only the temporary name of the same, which for me is no problem, but since there is no extension the file always arrives as something not readable to the recipient , however if you use something like this:

$mail->addAttachment($uploadfile, 'exemplo.jpg') , sending is done, the file name changes to "example.jpg" and makes the file readable to the recipient.

Can anyone tell me what error I'm making? I've already been looking for the extension via $_FILES['userfile']['type'] and replace with "example.jpg" but what returns me in the email is "image / jpeg" which does not define the extension, thus continuing the "empty" file.

Warning: I am using codeigniter.

This is my controller code:

if (array_key_exists('userfile', $_FILES)) {;

$uploadfile = tempnam(sys_get_temp_dir(), hash('sha256', $_FILES['userfile']['name']));

     if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
            var_dump($uploadfile);

            $file_type = $_FILES['userfile']['type'];

            $mail->addAttachment($uploadfile);

            if (!$mail->send()) {
                echo "Mailer Error: " . $mail->ErrorInfo;
            } else {
                echo "Message sent!";
            }
    } else {
            echo 'Failed to move file to ' . $uploadfile;
}

This is what is returned:

    
asked by anonymous 04.07.2018 / 17:55

1 answer

0

tempnam - Creates a unique file name

hash SHA-256 encrypts the file name, so the extension was pro beleleu:)

You can choose one of the solutions below:

if (array_key_exists('userfile', $_FILES)) {

  $uploadfile = tempnam(sys_get_temp_dir(), hash('sha256', $_FILES['userfile']['name']));

  $arquivo = $_FILES["userfile"];

  $ext = explode('.', basename($_FILES['userfile']['name']));
  $file_extension = end($ext);

  /***************** Nomes dos anexos ***************************/

  // Anexo com o nome original do arquivo                   
  //$mail->AddAttachment($arquivo['tmp_name'], $arquivo['name']  );

  // Anexo com o nome constituído pela variavel $uploadfile concatenado com a extensão original do arquivo
  $mail->AddAttachment($arquivo['tmp_name'], $uploadfile.".".$file_extension  );

 //anexo com novo nome e extensão original do arquivo
 //$mail->addAttachment($arquivo['tmp_name'], "NomeQualquer".".$file_extension);
    
04.07.2018 / 20:31