我通过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>
答案 0 :(得分:1)
将[]
添加到输入字段的名称中,如下所示:
<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
是下一个文件,依此类推。
这也是你如何获得同名的多个复选框的值。 (有关示例,请参阅this comment。
以下是循环上传文件的方法。
// 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 />";
}
}
注意我如何在$i
循环中使用for
来跟踪当前文件的索引。
(如果您想知道为什么我打电话给array_filter()
来获取计数,如果您没有上传任何文件,它看起来就像一个空白条目。array_filter()
删除该空白/无效条目。)
答案 1 :(得分:0)
尝试通过循环在每次迭代中为每个文件添加一个唯一的数字,如下所示:
$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" />