使用 php 和 phpmailer 发送和上传文件

Send and upload files with php and phpmailer

我不明白如何从我的联系表中加载和发送文件。我试图在 github 上搜索,但我不明白我必须在我的代码的哪一部分中插入它以及我必须插入什么。 这是 html 脚本的最后一部分。 我试着这样做,但现在它只给我发送了一个空文件。 感谢大家的帮助

<?php
$nome = $_POST["nome-locale"];
$email = $_POST["email"];
$telefono = $_POST["telefono"];
$indirizzo = $_POST["indirizzo"];
$civico = $_POST["civico"];
$citta = $_POST["citta"];
$provincia = $_POST["provincia"];
$cap = $_POST["cap"];
$newsletters = $_POST["newsletters"];
$uploadfile = tempnam(sys_get_temp_dir(), hash('sha256', $_FILES['userfile']['name']));






$body = "<br>nome-locale:" . $nome .  
       "<br>Email:" . $email .   
       "<br>TelefonoLocale:" . $telefono . 
     "<br>Indirizzo:" . $indirizzo . 
       "<br>Civico:" . $civico . 
     "<br>Città:" . $citta. 
     "<br>Provincia:" . $provincia .
     "<br>Cap:" . $cap . 
    "<br>newsletters:" . $newsletters;


use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;



require 'PHPMailer/src/Exception.php';
require 'PHPMailer/src/PHPMailer.php';
require 'PHPMailer/src/SMTP.php';
// Instantiation and passing `true` enables exceptions
$mail = new PHPMailer(true);

try {
    //Server settings
    
    $mail->isSMTP();                                            // Send using SMTP
    $mail->Host       = 'xxxx';                    // Set the SMTP server to send through
    $mail->SMTPAuth   = true;                                   // Enable SMTP authentication
    $mail->Username   = 'xxxx';                     // SMTP username
    $mail->Password   = 'xxxxxxx';                               // SMTP password
    $mail->SMTPSecure = 'ssl';                         // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` also accepted
    $mail->Port       = 465;                                    // TCP port to connect to

    //Recipients
    $mail->setFrom('xxxxxx', $name);
    $mail->addAddress('xxxxxxx');     // Add a recipient
    
    
  // Attach the uploaded file
        $mail->addAttachment($uploadfile, 'My uploaded file');

    // Content
    $mail->isHTML(true);                                  // Set email format to HTML
    $mail->Subject = 'Here is the subject';
    $mail->Body    = $body;
    $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
 
 
   
    
 

    $mail->send();
    echo '<script>
 alert("Messaggio inviato correttamente");
 window.history.go(-1);
 </script>';
} catch (Exception $e) {
    echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
?>
<div class="form-group was-validated ">
                   <label class="control-label" name="userfile" enctype="multipart/form-data">Menu1</label>
                <input type="file"  required>
  
</div>
      <div class="form-group was-validated ">
                   <label class="control-label">Menu2</label>
                <input type="file"  required>
   
     <hr>
     <div class="form-group was-validated  ">
      <div class="custom-control custom-checkbox mb-3" >
   <input  type="checkbox" class="custom-control-input" id="customControlValidation1"  required>
<label class="custom-control-label" for="customControlValidation1" ><small>Dichiaro di aver letto, accettato e di concordare con le <a href="https://www.google.it/" target="_blank" >Clausole Generali e l'Informativa sulla privacy.</a> Vaimenu.it permette ai locali e agli ospiti di comunicare tramite Vaimenu.it, che riceve ed elabora le comunicazioni in conformità con l'Informativa sulla privacy e le Clausole Generali di xxxx.</small></label>

       </div>
   
      <div class="form-group was-validated  ">
      <div class="custom-control custom-checkbox mb-3" >
   <input  type="checkbox" class="custom-control-input" id="customControlValidation2"  checked>
<label class="custom-control-label" for="customControlValidation2" name="newsletters" ><small>Voglio iscrivermi alla newsletter per ricevere promozioni ed altre comunicazione da parte di xxxxx</small></label>

      </div>
         
                <button class="btn btn-success btn-lg fa-pull-right" type="submit">Finito!<img src="img/star.svg" style="top: auto"></button>

我知道这 HTML 只是您表格的一部分,对吧? 询问,因为我看不到要输入的任何元素 email telefono cap 和其他一些元素。

另一件事是:

<label class="control-label" name="userfile" enctype="multipart/form-data">

通常无效 - 我的意思是:这里的属性 enctype 毫无意义,它实际上应该转到 <form> 元素(因为你说你的表单发送文件我认为它实际上工作只是文件问题是问题)。

您在这里遇到的主要问题是您如何处理上传的文件:

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

如果您尝试此代码(用于学习):

<?php
if (isset($_FILES['my-file'])) {
    var_dump($_FILES['my-file']);
    var_dump(tempnam(sys_get_temp_dir(), hash('sha256', $_FILES['my-file']['name'])));
}
?>
<!doctype html>
<html>
    <head>
        <title>sample</title>
    </head>
    <body>
        <form action="1.php" enctype="multipart/form-data" method="post">
            <input type='file' name='my-file'>
            <input type="submit">
        </form>
    </body>
</html>

你会注意到(文件上传后)是这样的:


array(5) {
  ["name"]=>
  string(21) "flight_to_hamburg.pdf"
  ["type"]=>
  string(15) "application/pdf"
  ["tmp_name"]=>
  string(14) "/tmp/phpS2dWIg"
  ["error"]=>
  int(0)
  ["size"]=>
  int(76044)
}
string(75) "/tmp/ecb918e45ff9059a9ad1b7b52c5c0d24575f8ac19474f2f13c908801eafaa48bLMlIeG"

这清楚地表明 sha256 不是 PHP 用于创建临时文件名称的内容。

因为 PHP Mailer 允许指向一个文件并以不同的名称发送它,那么在我的例子中它会很简单:

$path = $_FILES['my-file']['tmp_name']; //actual path to the file
$name = $_FILES['my-file']['name']; //actual name of the file
$mail->addAttachment($path, $name);

如果您想在发送后将文件存储在本地,请确保也调用 move_uploaded_file,如果不这样做,那么文件将会丢失。

因此在您的示例中它将是:

$path = $_FILES['userfile']['tmp_name']; //actual path to the file
$name = $_FILES['userfile']['name']; //actual name of the file
$mail->addAttachment($path, $name);

如果你出于某种原因想要对文件名进行 HASH,请在 $name 变量上进行; $path 必须指向现有文件。

此外,如果您没有任何 JavaScript 会在提交和发送文件时创建 FormData,仅使用标准浏览器对表单的处理,那么请务必更改您的其中一个:

<input type="file"  required>

<input type="file" name="userfile" required>

名称 必须匹配:这就是 PHP 识别从 HTML 表单的哪些字段发送了哪些数据的方式。