douyeke2695 2009-09-29 03:06
浏览 47
已采纳

用php发送附件

I am trying to create an email form that allows you to send an attachment. I have pieced code together from my PHP book and several websites.

When I send the email using this form the attachment ends up corrupted and the "$comments" don't seem to go through.

Here is the code I am using:

<?php
$to = $_POST['to'];
$from = $_POST['from'];
$re = $_POST['re'];
$comments= $_POST['comments'];

$att = $_FILES['att'];
$att_path= $_FILES['att']['tmp_name'];
$att_name = $_FILES['att']['name'];
$att_size = $_FILES['att']['size'];
$att_type = $_FILES['att']['type'];

//open, read, then close the file
$fp = fopen( $att_path, "rb" );
$file = fread( $fp, $att_size );
fclose($fp);

#create a boundary string
$num = md5(time());
$str = "==Multipart_Boumdary_x{$num}x";

//encode the data for transit
$file = chunk_split(base64_encode($file));

//define header
$hdr = "MIME-Versio: 1.0
";
$hdr .= "Content-Type: multipart/mixed; ";
$hdr .= "boundary=\"{$str}\"
";
$hdr .= "From: $from 
";

#define message
$msg = "This is a multi-part message in MIME format

";
$msg .= "--{$str}
";
$msg .= "Content-Type: text/plain; charset=\"iso-8859-1\"
";
$msg .= "Content-Transfer-Encoding: 8bit
";
$msg .= "$comments

";
$msg .= "--{$str}
";

#define the non-text attatchment
$msg .= "Content-Type: {$att_type}; ";
$msg .= "name=\"{$att_name}\"
";
$msg .= "Content-Disposition: attachment; ";
$msh .= "filename=\"{$att_name}\"
";
$msg .= "Content-Transfer-Encoding: base64
";
$msg .= "$file

";
$msg .= "--{$str}";

#sendmail
$ok = mail( $to, $re, $msg, $hdr );
if( $ok ) echo "OK";

?>

So, what am I doing wrong?

Thanks!

  • 写回答

4条回答 默认 最新

  • doz95923 2009-09-29 03:22
    关注

    Try this to encode your file for transit.

    Replace the line:

      $file = chunk_split(base64_encode($file));
    

    With:

      //Encode the file for transit
      $content = '';
      $fp = fopen($att_path, 'r'); 
      do { 
        $data = fread($fp, 8192); 
        if (strlen($data) == 0) break; 
        $content .= $data; 
      } while (true); 
      $file = chunk_split(base64_encode($content)); 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)