簡體   English   中英

在PHPMailer中添加多個附件

[英]Adding Multiple Attachments in PHPMailer

我試圖在附件中附加多個圖像。 我使用forearch作為每個附件但是,當我使用foreach時它沒有得到臨時名稱和名字,我可能做錯了。 以下是代碼和錯誤:

輸入HTML

<input id="upload-file" class="upload-file" type="file" name="upload-file[]">

var_dump $ _FILES ['upload-file']:

array(5) { ["name"]=> array(1) { [0]=> string(47) "WRANGLER_AW13_GIRLONTOP_A4_LANDSCAPE_300dpi.jpg" } ["type"]=> array(1) { [0]=> string(10) "image/jpeg" } ["tmp_name"]=> array(1) { [0]=> string(24) "C:\xampp\tmp\php41DC.tmp" } ["error"]=> array(1) { [0]=> int(0) } ["size"]=> array(1) { [0]=> int(91742) } } 

名稱和temp_name的var_dump:

Notice: Undefined index: name in C:\xampp\htdocs\hmg\process-email.php on line 66

Notice: Undefined index: tmp_name in C:\xampp\htdocs\hmg\process-email.php on line 67

NULL 
NULL

碼:

foreach($_FILES['upload-file'] as $file) {         

    $name = $file['name'];
    $path = $file['tmp_name'];
    var_dump($name);
    var_dump($path);

    //And attach it using attachment method of PHPmailer.

    $mail->addattachment($path,$name);
}

歡迎來到PHP的邪惡方面。 $_FILES不是那個,開發人員所期望的。

//wrong code
$img1 = $_FILES['upload-file'][0]['tmp_name'];
$img2 = $_FILES['upload-file'][1]['tmp_name'];

//working code
$img1 = $_FILES['upload-file']['tmp_name'][0];
$img2 = $_FILES['upload-file']['tmp_name'][1];

所以你需要類似的東西

$totalFiles = count($_FILES['upload-file']['tmp_name']);
for ($i = 0; $i < $totalFiles; $i++) {
   $name = $_FILES['upload-file']['name'][$i];
   $path = $_FILES['upload-file']['tmp_name'][$i];
   $mail->addattachment($path,$name);
}

以下是PHPMailer存儲庫中的一些示例

感謝所有的答案。 我相信你所有的方法都可以正常工作,但我決定自己解決。 這段代碼解決了這個問題

$validAttachments = array();

foreach($_FILES['upload-file']['name'] as $index => $fileName) {
    $filePath = $_FILES['upload-file']['tmp_name'][$index];
    $validAttachments[] = array($filePath, $fileName);              
}

foreach($validAttachments as $attachment) {
    $mail->AddAttachment($attachment[0], $attachment[1]);
}

我希望有同樣問題的人從這里得到一些幫助......

$i = '0';
foreach($_FILES['upload-file'] as $file) {
$name = $file['name'][$i];
$path = $file['tmp_name'][$i];
var_dump($name);
var_dump($path);
$mail->addattachment($path,$name);
$i++;
}

這里的大多數解決方案都基於表格。

如果你想附加特定目錄中的所有文件,我想出了一個簡單的解決方案。

$file_to_attach_directory = 'files/';
if ($handle = opendir($file_to_attach_directory)) {
    try {
        while (false !== ($entry = readdir($handle))) {
            $attachment_location = $file_to_attach_directory. $entry;
            $mail->addAttachment($attachment_location);
        }
        closedir($handle);
        // Send Mail
        if (!$mail->send()) {
        echo "Mailer Error: " . $mail->ErrorInfo;
        } else {
            echo "Message sent!";
        }
    } catch (Exception $e) {
        var_dump($e);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM