$from = "test@localhost.com";
$to = "test@localhost.com";
$subject =$_POST['subject'];
$message = $_POST['body'];
// include the from email in the headers
$headers = "From: $from";
// boundary
$time = md5(time());
$boundary = "==Multipart_Boundary_x{$time}x";
// headers used for send attachment with email
$headers .= "\nMIME-Version: 1.0\n" .
"Content-Type: multipart/mixed;\n" .
" boundary=\"{$boundary}\"";
// multipart boundary
$message = "--{$boundary}\n" .
"Content-Type: text/plain; charset=\"iso-8859-1\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n";
// Fily Type Validation
$allowedExtensions = array("jpeg","jpg");
// attach the attachments to the message
$files = $_FILES['imgupload'];
for($i=0; $i < count($files['name']); $i++)
{
if ($files['name'][$i] != '')
{
$file_name = $files['name'][$i];
$file_path = pathinfo($file_name);
$file_ext = $file_path['extension'];
if (in_array($file_ext, $allowedExtensions))
{
$tmp_name = $files['tmp_name'][$i];
$content = chunk_split(base64_encode(file_get_contents($tmp_name)));
$message .=
"--{$boundary}\n" .
"Content-Type: {\"application/octet-stream\"};\n" .
" name=\"{$file_name}\"\n" .
"Content-Disposition: attachment;\n" .
" filename=\"{$file_name}\"\n" .
"Content-Transfer-Encoding: base64\n\n" . $content . "\n\n";
} else { $errormgs= 'alert("File Type is not accepted, please use an image.")'; $formerrors = 'true'; }
} // else { $errormgs= 'alert("You Forgot to Attach the Photo")'; $formerrors = 'true'; }
}
// sending mail
if (!$formerrors)
{
$sendmail = mail($to, $subject, $message, $headers);
} else
{
print '<script type="text/javascript">';
print $errormgs;
print '</script>';
}
这是我编写的脚本,它允许您在表单中创建任意数量的输入字段,并将附件发送到专用电子邮件,而无需更改每个附加附件输入字段的PHP代码。
我唯一的问题是附件字段的警报。如果没有选择文件,我希望弹出窗口中包含要求添加图像的消息。由于某种原因,它不起作用。如果我添加带有消息的else语句,无论我是否添加图像,表单都会给我提醒。我做错了什么?
谢谢大家的帮助,如果我表达自己的话,对不起我的语言。