即使没有附加文件,也会发送PHP表单

时间:2015-02-05 18:58:35

标签: php forms

我正在使用教程中的以下代码发送附加到我网站上的表单的文件。我添加了一些缺失的变量,表单现在工作正常。但问题是我无法发送没有附加文件的表单,按下发送按钮浏览器后只显示一个没有消息的空白页面。

其他想想我希望你帮忙的是电子邮件地址。如果我写的是不正确的电子邮件地址,它会发送表单。

提前致谢。

<?php
if ($_SERVER['REQUEST_METHOD']=="POST"){

   $to="mymail@example.com";

   $subject="You have got an email from TGS";

   $from = stripslashes($_POST['fname'])."<".stripslashes($_POST['email']).">";

   if(empty($_POST['fname'])  || empty($_POST['email']) || empty($_POST['message']))
    {
        $errors .= "\n Error: all fields are required";
    }

    $fname = $_POST['fname'];
    $lname = $_POST['lname'];
    $email = $_POST['email'];
    $company = $_POST['company'];
    $phone = $_POST['phone'];
    $message = $_POST['message'];

    if (!eregi(    "^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email))
    {
        $errors .= "\n Error: Invalid email address";
    }

   $mime_boundary="==Multipart_Boundary_x".md5(mt_rand())."x";

   $tmp_name = $_FILES['filename']['tmp_name'];
   $type = $_FILES['filename']['type'];
   $file_name = $_FILES['filename']['name'];
   $size = $_FILES['filename']['size'];

   $message = "\n\n First Name: $fname \n\n Last Name: $lname \n\n Company: $company \n\n Phone: $phone \n\n Email: $email \n\nMessage: \n\n $message \n\nHere is your file: $file_name";

   if (file_exists($tmp_name)){

      if(is_uploaded_file($tmp_name)){

         $file = fopen($tmp_name,'rb');


         $data = fread($file,filesize($tmp_name));


         fclose($file);


         $data = chunk_split(base64_encode($data));
     }


      $headers = "From: $from\r\n" .
         "MIME-Version: 1.0\r\n" .
         "Content-Type: multipart/mixed;\r\n" .
         " boundary=\"{$mime_boundary}\"";


      $message = "This is a multi-part message in MIME format.\n\n" .
         "--{$mime_boundary}\n" .
         "Content-Type: text/plain; charset=\"iso-8859-1\"\n" .
         "Content-Transfer-Encoding: 7bit\n\n" .
         $message . "\n\n";

      $message .= "--{$mime_boundary}\n" .
         "Content-Type: {$type};\n" .
         " name=\"{$file_name}\"\n" .

         "Content-Transfer-Encoding: base64\n\n" .
         $data . "\n\n" .
         "--{$mime_boundary}--\n";

      if (@mail($to, $subject, $message, $headers))
      {         
        echo '<div><center><h1>Mail Sent successfully !!</h1></center></div>';         
      }else
      {
         echo '<div><center><h1>Error !! Unable to send Mail..</h1></center></div>';
      }
   }
}
?>

0 个答案:

没有答案