我使用php为我的网站构建了一个表单。提交表单后,内容将通过电子邮件发送给我,用户将被重定向到其他页面。当我完全填写表单时,代码工作正常。但是,其中一个字段是文件上传,当我不上传任何内容时,表单仍然发送但导致500内部服务器错误页面。如何在不上传文件时将表单重定向到正确的页面?我在下面加了我的代码
<?php
$email_to = "ashley@MyURL.com";
$email_subject = "Completed Questionnaire";
$name = $_POST['name'];
$gradyear = $_POST['gradyear'];
$hschool = $_POST['hschool'];
$hometown = $_POST['hometown'];
$email_from = $_POST['email'];
$DOB = $_POST['DOB'];
$GPA = $_POST['GPA'];
$height = $_POST['height'];
$weight = $_POST['weight'];
$about = $_POST['about'];
$message = "Form details below.\n\n";
function clean_string($string) {
$bad = array("content-type","bcc:","to:","cc:","href");
return str_replace($bad,"",$string);}
$message .= "Name: ".clean_string($name)."\n";
$message .= "Graduation Year: ".clean_string($gradyear)."\n";
$message .= "High School: ".clean_string($hschool)."\n";
$message .= "Hometown: ".clean_string($hometown)."\n";
$message .= "Email: ".clean_string($email_from)."\n";
$message .= "Date of Birth: ".clean_string($DOB)."\n";
$message .= "GPA: ".clean_string($GPA)."\n";
$message .= "Height: ".clean_string($height)."\n";
$message .= "Weight: ".clean_string($weight)."\n";
$message .= "About: ".clean_string($about)."\n";
/* GET File Variables */
$tmpName = $_FILES['attachment']['tmp_name'];
$fileType = $_FILES['attachment']['type'];
$fileName = $_FILES['attachment']['name'];
/* Start of headers */
$headers = "From: $email_from";
if (file($tmpName)) {
/* Reading file ('rb' = read binary) */
$file = fopen($tmpName,'rb');
$data = fread($file,filesize($tmpName));
fclose($file);
/* a boundary string */
$randomVal = md5(time());
$mimeBoundary = "==Multipart_Boundary_x{$randomVal}x";
/* Header for File Attachment */
$headers .= "\nMIME-Version: 1.0\n";
$headers .= "Content-Type: multipart/mixed;\n" ;
$headers .= " boundary=\"{$mimeBoundary}\"";
/* Multipart Boundary above message */
$message = "This is a multi-part message in MIME format.\n\n" .
"--{$mimeBoundary}\n" .
"Content-Type: text/plain; charset=\"iso-8859-1\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" .
$message . "\n\n";
/* Encoding file data */
$data = chunk_split(base64_encode($data));
/* Adding attchment-file to message*/
$message .= "--{$mimeBoundary}\n" .
"Content-Type: {$fileType};\n" .
" name=\"{$fileName}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n" .
"--{$mimeBoundary}--\n";
}
@mail($email_to, $email_subject, $message, $headers);
header("Location: http://myURL.com/contact.html");
?>
答案 0 :(得分:0)
在操作文件之前,您应首先检查文件是否确实已上传:
if ( ! empty($_FILES)) {
//file manipulation...
}