Phpmailer - Annex has no extension

Asked

Viewed 96 times

0

Good, when sending my attachment using Phpmailer, if I don’t add an extension after the variable, I can’t get the selected file extension:

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

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

Can anyone tell me what mistake I’m making? I’ve already picked up the extension via $_FILES['userfile']['type'] and replaced by "example.jpg" but what returns me in the email is "image/jpeg" which does not define the extension, thus continuing the file "empty".

Attention: I am using codeigniter.

This is my controller’s 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:

inserir a descrição da imagem aqui

  • From what I understand, you are creating a temp file (tempnam) and this file has extension .tmp. In view, his manipulation is incorrect.

1 answer

0

tempnam - Creates a unique filename

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

You can opt for 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);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.