[英]Third file is attached only, through phpmailer
我正在通过phpmailer发送带有多个附件的电子邮件。 我用来发送多个附件的循环是“带有附件的邮件”,仅包含最后选择的文件,而前两个或一个文件未发送。 Loop有问题吗? 请 :
foreach($_FILES as $key => $file){
$target_path = "uploads/";
$target_path = $target_path .basename($file['name']);
if(move_uploaded_file($file['tmp_name'], $target_path)) {
echo "the file ".basename($file['name'])." has been uploaded";
}else {
echo "there was an error";
}
mail->AddAttachment($target_path);
}
<form id=
"mail" name="mail" method="POST" action="<?php $PHP_SELF ?>"
enctype="multipart/form-data">
<input type="file" name="uploaded" multiple="" />
<input name="Submit1" type="submit" value="Submit" />
</form>
将[]
添加到输入字段的名称,如下所示:
<input type="file" name="uploaded[]" multiple="" />
每个文件使用相同的名称“上载”,因此“上载”将被处理的每个连续文件替换。 通过添加方括号,每个后续文件都将添加到“已上传”数组中。 这是添加[]
后得到的$_FILES
数组:
Array
(
[uploaded] => Array
(
[name] => Array
(
[0] => file4.txt
[1] => file1.txt
[2] => file2.txt
[3] => file3.txt
)
[type] => Array
(
[0] => text/plain
[1] => text/plain
[2] => text/plain
[3] => text/plain
)
[tmp_name] => Array
(
[0] => C:\temp\php95.tmp
[1] => C:\temp\php96.tmp
[2] => C:\temp\php97.tmp
[3] => C:\temp\php98.tmp
)
[error] => Array
(
[0] => 0
[1] => 0
[2] => 0
[3] => 0
)
[size] => Array
(
[0] => 7
[1] => 2850
[2] => 27
[3] => 231
)
)
)
每个数组中的索引0
是一个文件,每个数组中的索引1
是下一个文件,依此类推。
这也是获得相同名称的多个复选框的值的方式。 (有关示例,请参见此评论 。
这是循环浏览上载文件的方法。
// first get the count of how many files are uploaded
$numFiles = count(array_filter($_FILES['uploaded']['name']));
for ($i = 0; $i < $numFiles; ++$i) {
$target_path = 'c:/temp/' . basename($_FILES['uploaded']['name'][$i]);
if(move_uploaded_file($_FILES['uploaded']['tmp_name'][$i], $target_path)) {
echo "the file ".basename($_FILES['uploaded']['name'][$i])." has been uploaded<br />";
}
}
注意,我如何在for
循环中使用$i
来跟踪当前文件的索引。
(如果您想知道为什么我调用array_filter()
来获取计数,如果您不上传任何文件,则看起来空白条目会自动存在array_filter()
会删除该空白/无效条目。)
尝试通过循环将每次迭代的唯一编号添加到每个文件,如下所示:
$counter = 0;
foreach($_FILES as $key => $file){
$counter++;
$target_path = "uploads/";
$target_path = $target_path .basename($file['name'], ".jpg") . $counter . ".jpg";
if(move_uploaded_file($file['tmp_name'], $target_path)) {
echo "the file ".basename($file['name'])." has been uploaded";
}else {
echo "there was an error";
}
mail->AddAttachment($target_path);
}
<form id=
"mail" name="mail" method="POST" action="<?php $PHP_SELF ?>"
enctype="multipart/form-data">
<input type="file" name="uploaded" multiple="" />
<input name="Submit1" type="submit" value="Submit" />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.