generate and email with pdf file attached with php

Asked

Viewed 1,734 times

3

In my PHP script, I need to generate a PDF file and send it via email. I was able to send an attached file by email using phpmailer and generate a PDF in the browser using fpdf.

The problem is that I cannot attach the PDF to the email, since it is not being saved where it should be (on the winscp server).

$pdf->Output('f', 'arquivao.pdf');
$mail->AddAttachment('arquivao.pdf');
$enviado = $mail->Send();
  • 1

    My suggestion would be to test saving the file with an absolute path. It is possible that the FPDF is saving to a temporary folder where it is running and different from the one PHP is using. By controlling the absolute path you will always be sure where the file is and can correctly attach.

  • I think I was able to find out where the error is. In the FPDF implementation, it uses the file_get_content() function. I tried to run the function separately in a basic example, but the function did not run and the file was not created. I believe the error is linked to this function.

  • This seems to be a problem with the permissions where the FPDF is trying to write/read the file.

1 answer

1


Hi, Lucca, I would refer you to create a temporary file and, after sending, delete it from the server.

I took the liberty of including a function to generate the random name to complete the example.

function gerarIdentificadorLink($senha = 0, $tamanho = 20, $maiusculas = true, $numeros = true, $simbolos = false){
        // Caracteres de cada tipo
        $lmin = 'abcdefghijklmnopqrstuvwxyz';
        $lmai = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $num = '1234567890';
        $simb = '!@#$%*-';
        // Variáveis internas
        $retorno = '';
        $caracteres = '';
        // Agrupamos todos os caracteres que poderão ser utilizados
        $caracteres .= $lmin;
        if ($maiusculas) $caracteres .= $lmai;
        if ($numeros) $caracteres .= $num;
        if ($simbolos) $caracteres .= $simb;
        // Calculamos o total de caracteres possíveis
        $len = strlen($caracteres);
        for ($n = 1; $n <= $tamanho; $n++) {
        // Criamos um número aleatório de 1 até $len para pegar um dos caracteres
        $rand = mt_rand(1, $len);
        // Concatenamos um dos caracteres na variável $retorno
        $retorno .= $caracteres[$rand-1];
        }
        return $retorno;
}

/* Gera a string aleatoria */
$identificador = gerarIdentificadorLink();

/* Indica o caminho destino */
$Destino = '/var/www/html/';

/* Indica o nome temporário do arquivo */
$Arquivo = 'Arquivao_'.$identificador.'.pdf';

/* Cria a pasta temporária para armazenamento do arquivo */
if (!file_exists($Destino . $identificador)) {
   mkdir($Destino . $identificador);  
   $Destino = $Destino . $identificador . '/';
}

/* monta o caminho completo do arquivo */
$caminhoCompletoArquivo = $Destino . $Arquivo;

(...)

/* executa a geração do seu PDF*/
$pdf->Output('f', $caminhoCompletoArquivo);

/* adiciona o arquivo físico ao e-mail */
$mail->AddAttachment($caminhoCompletoArquivo);

/* envia o e-mail */
$enviado = $mail->Send();

/* exclui o arquivo pdf do servidor */
if (file_exists ($ArquivoCaminhoCompleto)) {
   unlink($ArquivoCaminhoCompleto);
}

I hope it helps.

  • First, thank you. But the problem is that I just can’t create the file on the server, because I can’t find the complete path.

  • Create a file meudir.php and put it in: <?php echo getcwd() . " n"; ? > - It will show you the way.

  • hello Andre. I was debugging the script when I discovered the cause of the error: the server denied permission for scripts trying to create files there. I will talk to my school (admin of the server) to help me solve. I appreciate your help!

  • Glad you were able to isolate the problem. If you want to buy some time, try the following code that changes the folder’s permission. It’s likely to work. Hug and success. <? php $folder = getcwd(); if(chmod($folder, 0755)){ echo 'Successfully modified permission. '; } Else { echo 'Unable to change permission'; } ?>

Browser other questions tagged

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