I'm having a load of trouble building a PHP form that will send an email attachment with the rest of the form info. I have no idea what I'm doing wrong. Every time I submit the form it fails to send. Please help. Thank you.
<?php
// hide all basic notices from PHP
error_reporting(E_ALL);
ini_set('display_errors', 1);
if(isset($_FILES) && (bool) $_FILES) {
$allowedExtensions = array("pdf","doc","docx","gif","jpeg","jpg","png","rtf","txt");
$files = array();
foreach($_FILES as $name=>$file) {
$file_name = $file['name'];
$temp_name = $file['tmp_name'];
$file_type = $file['type'];
$path_parts = pathinfo($file_name);
$ext = $path_parts['extension'];
if(!in_array($ext,$allowedExtensions)) {
die("File $file_name has the extensions $ext which is not allowed");
}
array_push($files,$file);
}
$date = $_POST['date'];
$namefirst = $_POST['first-name'];
$namelast = $_POST['last-name'];
$address1 = $_POST['street-address'];
$address2 = $_POST['street-address-line-2'];
$city = $_POST['city'];
$state = $_POST['state'];
$zip = $_POST['zip'];
$country = $_POST['country'];
$phone = $_POST['phone'];
$message = $_POST['message'];
// boundary
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
// headers for attachment
$headers .= "
MIME-Version: 1.0
" . "Content-Type: multipart/mixed;
" . " boundary=\"{$mime_boundary}\"";
// multipart boundary
$message1 = "This is a multi-part message in MIME format.
" . "--{$mime_boundary}
" . "Content-Type: text/plain; charset=\"iso-8859-1\"
" . "Content-Transfer-Encoding: 7bit
" . $message1 . "
";
$message1 .= "--{$mime_boundary}
";
// preparing attachments
for($x=0;$x<count($files);$x++){
$file = fopen($files[$x]['tmp_name'],"rb");
$data = fread($file,filesize($files[$x]['tmp_name']));
fclose($file);
$data = chunk_split(base64_encode($data));
$name = $files[$x]['name'];
$message1 .= "Content-Type: {\"application/octet-stream\"};
" . " name=\"$name\"
" .
"Content-Disposition: attachment;
" . " filename=\"$name\"
" .
"Content-Transfer-Encoding: base64
" . $data . "
";
$message1 .= "--{$mime_boundary}
";
}
if(!isset($hasError)) {
$emailTo = 'XXX';
$subject = 'New Submitted Message From: ' . $name;
$body = "Name: $namefirst $namelast
DOB: $date
Address: $address1
Address2: $address2
City: $city
State: $state
Zip Code: $zip
Country: $country
Phone: $phone
Message: $messsge";
$headers = 'From: ' .' <'.$emailTo.'>' . "
" . 'Reply-To: ' . $email;
mail($emailTo, $subject, $body, $headers);
$message = 'Thank you ' . $name . ', your message has been submitted.';
$result = true;
} else {
$arrMessage = array( $nameError, $emailError, $messageError );
foreach ($arrMessage as $key => $value) {
if( !isset($value) )
unset($arrMessage[$key]);
}
$message = implode( '<br/>', $arrMessage );
$result = false;
}
header("Content-type: application/json");
echo json_encode( array( 'message' => $message, 'result' => $result ));
die();
}
?>