我正在尝试在附件中附加多个图像。我已经为每个附件使用了 forearch,但是,当我使用 foreach 时它没有得到临时名称和名称,我可能做错了什么。下面是代码和错误:
输入网页
<input id="upload-file" class="upload-file" type="file" name="upload-file[]">
var_dump $_FILES["上传文件"]:
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:xampptmpphp41DC.tmp" } ["error"]=> array(1) { [0]=> int(0) } ["size"]=> array(1) { [0]=> int(91742) } }
姓名和temp_name var_dump:
Notice: Undefined index: name in C:xampphtdocshmgprocess-email.php on line 66
Notice: Undefined index: tmp_name in C:xampphtdocshmgprocess-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]);
}
我希望任何有同样问题的人都能从这里得到一些帮助......
这里的大多数解决方案都基于表单。
因此,如果您想附加特定目录中的所有文件,我想出了一个简单的解决方案。
$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);
}
}
$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++;
}