php - Send files with phpmailer before uploading them?


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)

           header("Location: " . $returnErrorPage);
             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"       
<p>Choose data (txt, html etc.):<br>
<input name="file" type="file" size="50" maxlength="100000" multiple>



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" ))

If everything went well I can delete the files after I have send the mail:


    foreach ($_FILES["file"]["error"] as $key => $error)
    $name = $_FILES["file"]["name"][$key];

header("Location: " . $returnPage);

Thank you for all your help!

People are also looking for solutions to the problem: javascript - Submit form after creating stripe token


Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.