上载的文件转到服务器,但不带有邮件附件

时间:2018-08-30 11:13:54

标签: php html html5 email

我是php编码的新手。 我的网站上有一个联系表,允许用户将文件作为附件发送到电子邮件。

从互联网上的参考文献中,我终于可以通过联系表发送电子邮件了。因此,问题是文件上传到服务器,但邮件到达时没有任何附件

我创建了一个名为upload的文件夹,并且文件只在那儿。 我错过了什么吗?下面是我正在使用的代码:

HTML:

<form action="send_form_email.php" method="post" enctype="multipart/form-data" name="servicesform" id="servicesform" autocomplete="on">
  <div class="control-group form-group">
    <div class="controls">
       <label class="contact-p1">Full Name:</label>
       <input type="text" class="form-control" name="yourname" id="yourname" required data-validation-required-message="Please enter your name.">
          <p class="help-block"></p>
       </div>
     </div>	
     <div class="control-group form-group">
       <div class="controls">
         <label class="contact-p1">Phone Number:</label>
         <input type="tel" class="form-control" name="phone" id="phone" required data-validation-required-message="Please enter your phone number.">
		 <p class="help-block"></p>
	   </div>
     </div>
     <div class="control-group form-group">
       <div class="controls">
         <label class="contact-p1">Email Address:</label>
         <input type="email" class="form-control" name="email" id="email" required data-validation-required-message="Please enter your email address.">
		 <p class="help-block"></p>
		</div>
      </div>
	  <div class="form-inputs">
		<p>Specify yourself</p>
		<select name="enquiring" required data-validation-required-message="Please select your field." >
          <option value="" > -- Please select -- </option>
          <option>Employer</option>
          <option>Employed</option>
          <option>Unemployed</option>
          <option>Student</option>
		</select>
        <div class="clearfix"></div>
	  </div>	
	<div class="form-inputs">
		<p>Choose your field</p>
		<select name="field" required data-validation-required-message="Please select your field." >
          <option value="" > -- Please select -- </option>
          <option>Banking</option>
          <option>Finance</option>
          <option>It</option>
          <option>Specialists</option>
		</select>
		<div class="clearfix"></div>
	  </div>			
						
	  <div class="form-inputs upload">
	     <p>Upload your resume</p>
		 <input type="file" id="uploads" name="uploads" multiple>
		 <div id="filedrag">Upload</div>
	  </div>
                    
      <!-- For success/fail messages -->
	 <button type="reset" name="reset" class="btn btn-primary">Reset</button>
     <button type="submit" class="btn btn-primary">Send</button>	
</form>

PHP:

<?php
    if(isset($_POST['email'])) {

        // TO AND FROM
        $email_to = "info@mysite.com";
        $email_subject = "Enquiry from my website";

        function died($error) {
            // ERROR MESSAGES TO THE USER
            echo "We are very sorry, but there were error(s) found with the form you submitted. ";
            echo "These errors appear below.<br /><br />";
            echo $error."<br /><br />";
            echo "Please go back and fix these errors.<br /><br />";
            die();
        }

        // VALIDATION ON EXPECTED DATA
        if(!isset($_POST['yourname']) ||
            !isset($_POST['phone']) ||
            !isset($_POST['email']) ||
            !isset($_POST['enquiring']) ||
            !isset($_POST['field'])) {
            died('We are sorry, but there appears to be a problem with the form you submitted.');      
        }

        $name_from = $_POST['yourname']; // required
        $phone = $_POST['phone']; // not required
		$email_from = $_POST['email']; // required
        $enquiring = $_POST['enquiring']; // not required
        $field = $_POST['field']; // not required
        $uploads = $_FILES['uploads']; // not required        
		
        // MANDATORY FIELDS 
        $error_message = "";
        $email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
          if(!preg_match($email_exp,$email_from)) {
            $error_message .= 'The email address you entered does not appear to be valid.<br />';
          }
            $string_exp = "/^[A-Za-z .'-]+$/";
          if(!preg_match($string_exp,$name_from)) {
            $error_message .= 'The name you entered does not appear to be valid.<br />';
          }
          if(strlen($error_message) > 0) {
            died($error_message);
          }
        $email_message = "Services Form.\n\n";

        function clean_string($string) {
          $bad = array("content-type","bcc:","to:","cc:","href");
          return str_replace($bad,"",$string);
        }

        $email_message .= "Name: ".clean_string($name_from)."\n";
		$email_message .= "Phone: ".clean_string($phone)."\n";
        $email_message .= "Email: ".clean_string($email_from)."\n";
        $email_message .= "I am ".clean_string($enquiring)."\n";
        $email_message .= "field: ".clean_string($field)."\n";


        // FILE UPLOADS
        $allowedExts = array("ai", "doc", "docx", "gif", "jpeg", "jpg", "pdf", "png", "psd");
        $extension = end(explode(".", $_FILES["uploads"]["name"]));
		if ((($_FILES["uploads"]["type"] == "image/gif")
        || ($_FILES["uploads"]["type"] == "image/jpeg")
        || ($_FILES["uploads"]["type"] == "image/png")
        || ($_FILES["uploads"]["type"] == "image/pjpeg"))
        || ($_FILES["uploads"]["size"] < 200000) 
		&& in_array($extension, $allowedExts)) {
		if ($_FILES["uploads"]["error"] > 0) {
             echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
             }
           else {
              echo "Upload: " . $_FILES["uploads"]["name"] . "<br />";
              echo "Type: " . $_FILES["uploads"]["type"] . "<br />";
              echo "Size: " . ($_FILES["uploads"]["size"] / 1024) . " Kb<br />";
              echo "Temp file: " . $_FILES["uploads"]["tmp_name"] . "<br />";
                 if (file_exists("upload/" . $_FILES["uploads"]["name"])) {
                    echo $_FILES["uploads"]["name"] . " already exists. ";
           }
              else {
                move_uploaded_file($_FILES["uploads"]["tmp_name"],
                 "upload/" . $_FILES["uploads"]["name"]);
                 echo "Stored in: " . "upload/" . $_FILES["uploads"]["name"];
              }
           }
        }
			else {
           echo "Invalid file";
        }
		


    // EMAIL HEADERS
    

    $headers .= "From:".$from_email."\r\n"; // Sender Email
    'Reply-To: '.$email_from."\r\n" .
    'X-Mailer: PHP/' . phpversion();
    @mail($email_to, $email_subject, $email_message, $headers);


?>

<!-- SUCCESS MESSAGE -->

		<?php
		header("Location: thank-you.html");
exit();
		?>
Your message has been sent.  Thank you for contacting us, We'll get back to you as soon as possible.

<?php
}
?>

1 个答案:

答案 0 :(得分:0)

因此,正如我在评论中所说,您应该使用Swift MailerPHPMailer。我对您的代码进行了一些修复,但是仍然有一些部分不是很好。

最重要的是:不要重新发明轮子-已经有很棒的邮件库。 mail()函数仅应用作库的基础层,切勿发送带有代码的电子邮件。

我做了什么:

  • filter_var()代替了正则表达式检查
  • 使用更易读的内容编辑了扩展名和mime类型检查
  • 添加了发送附件所需的代码(没有对其进行测试,它可能无法按预期工作,但应该可以)
  • 用短数组语法(array())替换了长数组语法([]

我没有做的事情:

  • 我没有完善您的代码,以使其更具可读性
  • 我没有解决文件移动的问题(您不应该使用相对路径,所以最好使用类似move_uploaded_file($_FILES["uploads"]["tmp_name"], __DIR__."/upload/" . $_FILES["uploads"]["name"]);的东西)

无论如何,这是您的代码。

<?php
if (isset($_POST['email'])) {

    // TO AND FROM
    $emailTo = "info@mysite.com";
    $emailSubject = "Enquiry from my website";

    function died($error)
    {
        // ERROR MESSAGES TO THE USER
        echo "We are very sorry, but there were error(s) found with the form you submitted. ";
        echo "These errors appear below.<br /><br />";
        echo $error . "<br /><br />";
        echo "Please go back and fix these errors.<br /><br />";
        die();
    }

    // VALIDATION ON EXPECTED DATA
    if (!isset($_POST['yourname']) ||
        !isset($_POST['phone']) ||
        !isset($_POST['email']) ||
        !isset($_POST['enquiring']) ||
        !isset($_POST['field'])) {
        died('We are sorry, but there appears to be a problem with the form you submitted.');
    }

    $nameFrom = $_POST['yourname']; // required
    $phone = $_POST['phone']; // not required
    $emailFrom = $_POST['email']; // required
    $enquiring = $_POST['enquiring']; // not required
    $field = $_POST['field']; // not required
    $uploads = $_FILES['uploads']; // not required

    // MANDATORY FIELDS
    $errorMessage = "";
    if (!filter_var($emailFrom, FILTER_VALIDATE_EMAIL)) {
        $errorMessage .= 'The email address you entered does not appear to be valid.<br />';
    }
    // commented out, users whose names include special characters (á, ý, etc.) would be filtered out
//    $stringExp = "/^[A-Za-z .'-]+$/";
//    if (!preg_match($stringExp, $nameFrom)) {
//        $errorMessage .= 'The name you entered does not appear to be valid.<br />';
//    }
    if (strlen($errorMessage)) {
        died($errorMessage);
    }
    $emailMessage = "Services Form.\n\n";

    function clean_string($string)
    {
        $bad = ["content-type", "bcc:", "to:", "cc:", "href"];
        return str_replace($bad, "", $string);
    }

    $emailMessage .= "Name: " . clean_string($nameFrom) . "\n";
    $emailMessage .= "Phone: " . clean_string($phone) . "\n";
    $emailMessage .= "Email: " . clean_string($emailFrom) . "\n";
    $emailMessage .= "I am " . clean_string($enquiring) . "\n";
    $emailMessage .= "field: " . clean_string($field) . "\n";


    // FILE UPLOADS
    $allowedExts = ["ai", "doc", "docx", "gif", "jpeg", "jpg", "pdf", "png", "psd"];
    $allowedMimeTypes = [
        "image/gif",
        "image/jpeg",
        "image/png",
        "image/pjpeg"
    ];
    $extension = pathinfo($_FILES["uploads"]["name"], PATHINFO_EXTENSION);
    if (in_array($_FILES["uploads"]["type"], $allowedMimeTypes) && $_FILES["uploads"]["size"] < 200000 && in_array($extension, $allowedExts)) {

        if ($_FILES["uploads"]["error"] > 0) {
            echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
        } else {
            echo "Upload: " . $_FILES["uploads"]["name"] . "<br />";
            echo "Type: " . $_FILES["uploads"]["type"] . "<br />";
            echo "Size: " . ($_FILES["uploads"]["size"] / 1024) . " Kb<br />";
            echo "Temp file: " . $_FILES["uploads"]["tmp_name"] . "<br />";
            if (file_exists("upload/" . $_FILES["uploads"]["name"])) {
                echo $_FILES["uploads"]["name"] . " already exists. ";
            } else {
                move_uploaded_file($_FILES["uploads"]["tmp_name"], "upload/" . $_FILES["uploads"]["name"]);
                echo "Stored in: " . "upload/" . $_FILES["uploads"]["name"];
            }
        }
    } else {
        echo "Invalid file";
    }

    $filePath = "upload/" . $_FILES["uploads"]["name"];
    $fileContent = chunk_split(base64_encode(file_get_contents($filePath)));

    $separator = md5(random_int(PHP_INT_MIN, PHP_INT_MAX));

    $eol = "\r\n";


    // EMAIL HEADERS

    $headers = "";
    $body = "";

    $headers .= "From: {$emailFrom}{$eol}";// Sender Email
    $headers .= "Reply-To: {$emailFrom}{$eol}";
    $headers .= "X-Mailer: PHP/" . phpversion() . $eol;
    $headers .= "MIME-Version: 1.0{$eol}";
    $headers .= "Content-Type: multipart/mixed; boundary=\"{$separator}\"{$eol}";
    $headers .= "Content-Transfer-Encoding: 7bit{$eol}";
    $headers .= "This is a MIME encoded message.{$eol}";

    // the text message
    $body .= "--{$separator}{$eol}";
    $body .= "Content-Type: text/plain; charset=\"utf-8\"{$eol}";
    $body .= "Content-Transfer-Encoding: 8bit{$eol}";
    $body .= $emailMessage . $eol;

    // the attachment
    $body .= "--{$separator}{$eol}";
    $body .= "Content-Type: {$_FILES["uploads"]["type"]}; name=\"{$_FILES["uploads"]["name"]}\"{$eol}";
    $body .= "Content-Transfer-Encoding: base64{$eol}";
    $body .= "Content-Disposition: attachment{$eol}";
    $body .= $fileContent . $eol;
    $body .= "--{$separator}--";

    @mail($emailTo, $emailSubject, $body, $headers);


    ?>

    <!-- SUCCESS MESSAGE -->

    <?php
    header("Location: thank-you.html");
    exit();
    ?>
    Your message has been sent.  Thank you for contacting us, We'll get back to you as soon as possible.

    <?php
}