I have some web forms that contain several normal fields, and at least one upload field each. Upon submission, the contents of the form are e-mailed to the recipient. When I fill out the form without including a file for upload, it works correctly. I get an e-mail that, when opened, lists the field names and their values, like Field Name: value.
However, if I do include a file for upload, instead of getting an e-mail that contains the normal fields as "Field Name: fieldvalue" along with an attachment for the file I uploaded, I receive a blank e-mail that just contains an attachment. The attachment is always called noname (yes, there is no extension), and it contains the entire contents of the e-mail, including the Field Name: value pairs, and the still-encoded attached file.
I've never written PHP to send attachments with an e-mail before, so I'm not sure where the mistake is. Here is my code:
<?php
$body = "
<ul>
<li>Field name: value</li>
<li>Field name: value</li>
</ul>
<!-- etc. -->
";
$hasFile = false;
// check if $_FILES superglobal has content
if( isset($_FILES['claim_upload']['tmp_name']) && !empty($_FILES['claim_upload']['tmp_name']) ) {
$fileatt = $_FILES['claim_upload']['tmp_name']; // get file's temp name
$fileatt_type = $_FILES['claim_upload']['type']; // get file's type
$fileatt_name = $_FILES['claim_upload']['name']; // get file's name
if( is_uploaded_file($fileatt) ) { // check if file was uploaded
$file = fopen($fileatt,'rb'); // open file, read content, close
$fileatt_data = fread( $file, filesize($fileatt) );
fclose($file);
$hasFile = true; // we have an uploaded file
}
}
/*** Set up e-mail ***/
$to = "email@email.email";
$subject = "My Email Form";
$headers = 'MIME-Version: 1.0' . "\n";
if($hasFile) {
$boundary_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$boundary_rand}x";
$body = "--".$mime_boundary
."\nContent-Type: text/plain;"
."charset=\"iso-8859-1\"\n"
."Content-Transfer-Encoding: 7bit\n\n"
.$body."\n\n";
$fileatt_data = chunk_split( base64_encode($fileatt_data) );
$body .= "--{$mime_boundary}\n"
."Content-Type: {$fileatt_type};\n"
."name=\"{$fileatt_name}\"\n"
."Content-Disposition: attachment;\n"
." filename=\"{$fileatt_name}\"\n"
."Content-Transfer-Encoding: base64\n\n"
.$fileatt_data."\n\n"
."--{$mime_boundary}--\n";
$headers .= 'Content-type: multipart/mixed; \n boundary="'.$mime_boundary.'"\n';
} else
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= "From: senderemail@email.email"."\r\n";
mail($to, $subject, $body, $headers);
?>