fopen multiple files to send mail with mail() php

739 views Asked by At

i have problems to send mail with multiple files with mail() php. Until now, only send the first file, so i need your help please. Give you my code:

HTML:

<form action="colabora.php" method="post" enctype="multipart/form-data">

[...]

<div id="adjuntos">
<input type="file" name="archivos[]" class="form-control"/>
</div>

[...]

PHP:

[...]

if (isset ($_FILES["archivos"])) {
  $tot = count($_FILES["archivos"]["name"]);
  for ($i = 0; $i < $tot; $i++){
    $_name=$_FILES["archivos"]["name"][$i];
    $_type=$_FILES["archivos"]["type"][$i];
    $_size=$_FILES["archivos"]["size"][$i];
    $_temp=$_FILES["archivos"]["tmp_name"][$i]; 

    //FILES EXISTS
    if(strcmp($_name, "")){
      $fp = fopen($_temp, "rb");
      $file = fread($fp, $_size);
      $file = chunk_split(base64_encode($file)); 
    }

    // FILES HEADERS 
    $headers .= "Content-Type:application/octet-stream ";
    $headers .= "name=\"".$_name."\"r\n";
    $headers .= "Content-Transfer-Encoding: base64\r\n";
    $headers .= "Content-Disposition: attachment; ";
    $headers .= "filename=\"".$_name."\"\r\n\n";
    $headers .= "".$file."\r\n";
    $headers .= "--".$num."--";
  }
}

[...]

mail($para, $asunto, $body, $headers)

2

There are 2 answers

3
umka On BEST ANSWER

I've noted you have lost a boundary before each attachment.

// FILES HEADERS 
$headers .= "--".$num."\r\n";  // Boundary
$headers .= "Content-Type:application/octet-stream ";
$headers .= "name=\"".$_name."\"r\n";
$headers .= "Content-Transfer-Encoding: base64\r\n";
$headers .= "Content-Disposition: attachment; ";
$headers .= "filename=\"".$_name."\"\r\n\n";
$headers .= $file."\r\n";

The closing boundary (ended with "--") should be placed outside the loop:

$headers .= "--".$num."--\r\n";
0
manugr9 On

There is something here that causes it. Show contents of $body right after files:

$headers .= "Content-Type:application/octet-stream ";
$headers .= "name=\"".$_name."\"r\n";       
$headers .= "Content-Transfer-Encoding: base64\r\n";
$headers .= "Content-Disposition: attachment; ";
$headers .= "filename=\"".$_name."\"\r\n\n";
$headers .= "".$file."\r\n";
$headers .= "--".$num."\r\n";