I have this PHP code which sends an email with an attachment along with form values that get passed through (I removed this section to make it easier to read). The code works but it submits a blank text file as an attachment if the user does not select an attachment.
Is there any way to have it just not attach anything if no attachment is selected?
php:
<?php
//if there is post
if(isset($_POST) && !empty($_POST) ) {
// if thre is an attachment
$_FILES['attachment']['name'];
// store some variables
$file_name = $_FILES['attachment']['name'];
$temp_name = $_FILES['attachment']['tmp_name'];
$file_type = $_FILES['attachment']['type'];
// get the extension of the file
$base = basename($file_name);
$extension = substr($base, strlen($base)-4, strlen($base));
// only allow these file types
$allowed_extensions = array(".doc", "docx", ".pdf", ".zip", ".csv", ".xls", "xlsx", "");
// check that this file type is allowed
if(in_array($extension,$allowed_extensions)) {
// mail essentials
$from = $_POST['email'];
// multiple recipients
$to = 'email@email.com,'.$_POST['email'];
// subject
$today_day=date("d") ;
$today_month=date("m") ;
$today_year=date("Y") ;
$subject = 'Confirmation: '
. " Date and Time: ".$_POST['ScheduledMonth']."/".$_POST['ScheduledDay']."/". $_POST['ScheduledYear']
. ' at '. $_POST['ScheduledHour'].":".$_POST['ScheduledMin']." ".$_POST['AMPM']." ".$_POST['TimeZone'];
// message
$message = 'HTML message goes here';
// things you need
$file = $temp_name;
$content = chunk_split(base64_encode(file_get_contents($file)));
$uid = md5(uniqid(time()));
//standard mail headers
$header = "From: ".$from."
";
$header .= "Reply-To: ".$replyto."
";
$header .= "MIME-Version: 1.0
";
// declaring we have multiple parts of email (i.e plain text and attachment)
$header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"
";
$header .= "This is a multi-part message in MIME format.
";
// text part
$header .= "--".$uid."
";
$header .= 'Content-type: text/html; charset=iso-8859-1' . "
";
$header .= "Content-Transfer-Encoding: 7bit
";
$header .= $message."
";
// file attachment
$header .= "--".$uid."
";
$header .= "Content-Type: ".$file_type."; name=\"".$file_name."\"
";
$header .= "Content-Transfer-Encoding: base64
";
$header .= "Content-Disposition: attachment filename=\"".$file_name."\"
";
$header .= $content."
";
//send the mail
if (mail($to, $subject, "", $header)) {
//redirect to the thank you page
header('Location: http://www.somesite.com/thankyou.php');
} else {
echo "Fail";
}
} else {
echo "file type not allowed";
}
}
?>