PHP邮件脚本错误

时间:2012-02-01 21:20:01

标签: php email attachment

我有一个提交页面,其中客户端扫描使用附加的邮件程序脚本提交可填写的PDF表单和照片。表单正确上传到服务器,但是当它发送到客户端时,PDF是空白的。

<?php
// did files get sent
if(isset($_FILES) && (bool) $_FILES) {

  // define allowed extensions
  $allowedExtensions = array("pdf","doc","docx","gif","jpeg","jpg","png","rtf","txt");
  $files = array();

  // loop through all the files
  foreach($_FILES as $name=>$file) {

     // define some variables
     $file_name = $file['name']; 
     $temp_name = $file['tmp_name'];

     // check if this file type is allowed
     $path_parts = pathinfo($file_name);
     $ext = $path_parts['extension'];
     if(!in_array($ext,$allowedExtensions)) {
        die("extension not allowed");
     }

     // move this file to the server YOU HAVE TO DO THIS
     $server_file = "/home/castmeb1/public_html/uploads/$path_parts[basename]";
     move_uploaded_file($temp_name,$server_file);

     // add this file to the array of files
     array_push($files,$server_file);
  }  

  // define some mail variables
  $to = "castmebg@gmail.com";
  $from = "castmebg@gmail.com"; 
  $subject ="test attachment"; 
  $msg = "Please see attached";
  $headers = "From: $from";

  // define our boundary
  $semi_rand = md5(time()); 
  $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";

  // tell the header about the boundary
  $headers .= "\nMIME-Version: 1.0\n";
  $headers .= "Content-Type: multipart/mixed;\n";
  $headers .= " boundary=\"{$mime_boundary}\""; 

  // part 1: define the plain text email
  $message ="\n\n--{$mime_boundary}\n";
  $message .="Content-Type: text/plain; charset=\"iso-8859-1\"\n";
  $message .="Content-Transfer-Encoding: 7bit\n\n" . $msg . "\n\n";
  $message .= "--{$mime_boundary}\n";

  // part 2: loop and define mail attachments
  foreach($files as $file) {
     $aFile = fopen($file,"rb");
     $data = fread($aFile,filesize($file));
     fclose($aFile);
     $data = chunk_split(base64_encode($data));
     $message .= "Content-Type: {\"application/octet-stream\"};\n";
     $message .= " name=\"$file\"\n";
     $message .= "Content-Disposition: attachment;\n";
     $message .= " filename=\"$file\"\n";
     $message .= "Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
     $message .= "--{$mime_boundary}\n";
  }

  // send the email
  $ok = mail($to, $subject, $message, $headers); 
  if ($ok) { 
     echo "<p>mail sent to $to!</p>"; 
  } else { 
     echo "<p>mail could not be sent!</p>"; 
  }
  die();
}
?>

谢谢,

JB

1 个答案:

答案 0 :(得分:0)

if(isset($_FILES) && (bool) $_FILES) {

是成功上传的无效测试。始终设置$ _FILES数组,假设文件上传为ATTEMPT,则该数组永远不会为空。

你应该检查这样的错误:

if ($_FILES['name_of_file_field']['error'] === UPLOAD_ERR_OK) {
   ... file was successfully uploaded ...
}

错误代码在此处定义:http://php.net/manual/en/features.file-upload.errors.php