问题
I have a problem with sending emails with attachment by the phpmailer script. I have a working code if I want to add a single file to the mail. But when it comes to multiple files, it looks like they are not even uploaded.
My code for a single file:
if (isset($_FILES['file']) &&
$_FILES['file']['error'] == UPLOAD_ERR_OK)
{
$mail->AddAttachment($_FILES['file']['tmp_name'],
$_FILES['file']['name']);
if(!$mail->Send())
{
header("Location: " . $returnErrorPage);
}
else
{
header("Location: " . $returnHomePage);
}
}
I tried a few codes that should loop through all files in $_FILES without success. Then I tested the following code:
$count = count($_FILES['file']['tmp_name']);
echo $count;
it returns 0. I know that $_FILES is empty, but I dont know the reason for that. Do I need to buffer the files or something like that?
EDIT: here is my html code which sent the files and other data to the script:
<form id="form_907007" class="appnitro" method="post" action="server/phpmailer.php"
enctype="multipart/form-data">
<p>Choose data (txt, html etc.):<br>
<input name="file" type="file" size="50" maxlength="100000" multiple>
</p>
</form>
回答1:
The solution of my problem is based on the idea from Synchro, upload the files first and then send the email.
In my html code I had to change this line:
<input name="file" type="file" size="50" maxlength="100000" multiple>
<input name="file[]" type="file" size="50" maxlength="100000" multiple>
it is important to do this little step to reach each file you want to upload later in php.
The second step is to loop through all files an store them on your server. This is the way I did that:
foreach ($_FILES["file"]["error"] as $key => $error){
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["file"]["tmp_name"][$key];
$name = $_FILES["file"]["name"][$key];
move_uploaded_file($tmp_name," server/data/$name"}
In the next step I check if the files are uploaded successful, if return = TRUE I add them as attachement to the mail:
if(move_uploaded_file($tmp_name,"server/data/$name" ))
{
$mail->AddAttachment("server/data/$name");
}
If everything went well I can delete the files after I have send the mail:
if($mail->Send()){
foreach ($_FILES["file"]["error"] as $key => $error)
{
$name = $_FILES["file"]["name"][$key];
unlink("$name");
}
header("Location: " . $returnPage);
exit;}
Thank you for all your help!
来源:https://stackoverflow.com/questions/26236259/send-files-with-phpmailer-before-uploading-them